Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
Example 1:Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
Example 2:Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9
Constraints:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
The key is using set in while which the while loop would run if the set is not empty.
If you use the set in for loop, then you cannot modify the set in a loop.
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
check_set = set(nums)
max_length = 0
while check_set:
low = high = num = check_set.pop()
while high + 1 in check_set or low - 1 in check_set:
if high+1 in check_set:
high += 1
check_set.remove(high)
if low - 1 in check_set:
low -= 1
check_set.remove(low)
max_length = max(high - low + 1, max_length)
return max_length
搶先發佈留言