给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
用set做
class Solution: def longestConsecutive(self, nums: List[int]) -> int: if not nums oor len(nums)==0: return 0 a =set(nums) res = 0 for i in range(0,len(nums)): if a and nums[i] in a: a.remove(nums[i]) low,high = nums[i],nums[i] low-=1 while low in a: a.remove(low) low-=1 high+=1 while high in a: a.remove(high) high+=1 res = max(res,high-low-1) return res