题目来源:
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):
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = {}
ans = 0
if len(nums) != 0: ans = 1
for i in nums:
#ans = max(ans,1)
if i in count: continue
count[i] = [i,i]
if i - 1 in count:
#print(i - 1,count[i - 1])
count[count[i - 1][0]][1],count[i][0] = count[i][1],count[i - 1][0]
#print(count[i - 1][0],count[count[i - 1][0]],i,count[i])
ans = max(ans,count[count[i - 1][0]][1] + 1 - count[count[i - 1][0]][0])
if i + 1 in count:
#print(i + 1,count[i + 1])
count[count[i + 1][1]][0],count[count[i][0]][1] = count[i][0],count[i+1][1]
ans = max(ans,count[count[i + 1][1]][1] - count[count[i + 1][1]][0] + 1)
#print(count[i + 1][1],count[count[i + 1][1]],count[i][0],count[count[i][0]])
#for i in count:
#print(i,count[i])
#ans = max(ans,count[i][1] - count[i][0] + 1)
return ans