1 """ 2 Given an unsorted array of integers, find the length of the longest consecutive elements sequence. 3 Your algorithm should run in O(n) complexity. 4 Example: 5 Input: [100, 4, 200, 1, 3, 2] 6 Output: 4 7 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. 8 """ 9 """ 10 解法一:关键用了自查找的想法,找到以后删除,节省时间 11 将nums用set处理一下,然后看成一个队列 12 首先将nums[0]出队列 13 令 j = nums[0]+1 ,判断nums[0]右边的连续数字是否在nums中, 14 如果存在:将nums[j]从数组中移除remove, j=j+1, 数字增大继续检查是否在nums中, 15 令 i = nums[0]-1, 判断nums[0]左边的连续数字是否在nums中, 16 如果存在:将nums[i]从数组中移除remove, i=i-1, 数字减小继续检查是否在nums中 17 用res=max(res, j-i-1)记录最大长度 18 """ 19 class Solution1: 20 def longestConsecutive(self, nums): 21 nums = set(nums) 22 res = 0 23 while nums: 24 n = nums.pop() 25 j = n+1 #!!!这种自查找式的思路很新颖 26 while j in nums: 27 nums.remove(j) 28 j += 1 29 i = n-1 #!!! 30 while i in nums: 31 nums.remove(i) 32 i -= 1 33 res = max(res, j-i-1) 34 return res 35 """ 36 利用dict(),以数组中每个值为key,以该值往后连续序列为value,默认为1 37 并将i+1遍历后的数值删去 38 """ 39 class Solution2: 40 def longestConsecutive(self, nums): 41 d = dict() 42 res = 0 43 for num in nums: 44 d[num] = 1 45 for num in nums: 46 if num in d: 47 temp = num+1 48 while temp in d: 49 d[num] += d[temp] 50 d.pop(temp) 51 temp += 1 52 res = max(res, d[num]) 53 return res