题目来源:
https://leetcode.com/problems/longest-consecutive-sequence/
题意分析:
给定一个没有排好序的数组,找到最长的连续序列的长度。要求时间复杂度是O(n)。比如[100, 4, 200, 1, 3, 2],其最长长度是[1,2,3,4]长度为4.
题目思路:
对于每个数记录他所在的目前最长的序列,将其±1,如果其也在给定序列中,那么更新他所在的最长序列,比如上面的例子。所对应的序列变化是:
1. 100:[100,100];
2.100:[100,100];4:[4,4];
3.100:[100,100];4:[4,4];200:[200,200];
4.100:[100,100];4:[4,4];200:[200,200];1:[1,1];
5. 100:[100,100];4:[3,4];200:[200,200];1:[1,1];3 :[3,4];
6.100:[100,100];4:[1,4];200:[200,200];1:[1,4];3 :[3,4],2:[1,2];
所以得到答案是4
代码(python):

1 class Solution(object): 2 def longestConsecutive(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 count = {} 8 ans = 0 9 if len(nums) != 0: ans = 1 10 for i in nums: 11 #ans = max(ans,1) 12 if i in count: continue 13 count[i] = [i,i] 14 if i - 1 in count: 15 #print(i - 1,count[i - 1]) 16 count[count[i - 1][0]][1],count[i][0] = count[i][1],count[i - 1][0] 17 #print(count[i - 1][0],count[count[i - 1][0]],i,count[i]) 18 ans = max(ans,count[count[i - 1][0]][1] + 1 - count[count[i - 1][0]][0]) 19 if i + 1 in count: 20 #print(i + 1,count[i + 1]) 21 count[count[i + 1][1]][0],count[count[i][0]][1] = count[i][0],count[i+1][1] 22 ans = max(ans,count[count[i + 1][1]][1] - count[count[i + 1][1]][0] + 1) 23 #print(count[i + 1][1],count[count[i + 1][1]],count[i][0],count[count[i][0]]) 24 #for i in count: 25 #print(i,count[i]) 26 #ans = max(ans,count[i][1] - count[i][0] + 1) 27 return ans 28