From d98aef7690fb93fba16a37f10aeba8d7cdd1e2f7 Mon Sep 17 00:00:00 2001 From: bumpsoo Date: Tue, 29 Oct 2024 00:23:37 +0900 Subject: [PATCH] https://leetcode.com/problems/longest-square-streak-in-an-array --- medium/longest_square_streak_in_an_array.py | 35 +++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 medium/longest_square_streak_in_an_array.py diff --git a/medium/longest_square_streak_in_an_array.py b/medium/longest_square_streak_in_an_array.py new file mode 100644 index 0000000..2ba03f6 --- /dev/null +++ b/medium/longest_square_streak_in_an_array.py @@ -0,0 +1,35 @@ +# https://leetcode.com/problems/longest-square-streak-in-an-array +from typing import List + +class Solution: + def longestSquareStreak(self, nums: List[int]) -> int: + nums.sort() + s = set() + ret = 0 + for each in nums: + if each in s: + continue + curr = each + l = 1 + while curr * curr <= 10 ** 5: + if self.search(nums, curr * curr): + curr *= curr + s.add(curr) + l += 1 + else: + break + ret = max(l, ret) + return ret if ret >= 2 else - 1 + + def search(self, nums: List[int], num: int) -> bool: + left, right = 0, len(nums) - 1 + while left <= right: + mid = (left + right) // 2 + if nums[mid] == num: + return True + if nums[mid] < num: + left = mid + 1 + else: + right = mid - 1 + return False +