Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
给定一个未排序的数组,找到最长的连续整数序列~要求复杂度为O(n)~最直观的解法是先排序,然后扫描一遍数组,得到最长的连续整数序列,但复杂度是O(nlogn)~ 另外一个解法是:把数组存到dictionary里,dict的key是数组里的数,对应的value代表这个数是否被访问过;然后遍历所有的key,如果这个数没有被访问过,就不断找寻key+1和key-1得到的值是否存在dict中, 然后比较并更新最长的连续序列长度,注意把已访问过的元素的value标记为True~因为用dictionary读取数的平均时间复杂度为O(1),所以这种解法的复杂度为O(n + n) = O(n)
class Solution:
# @param num, a list of integer
# @return an integer
def longestConsecutive(self, num):
if num is None or len(num) == 0: return 0
dict = {nums:False for nums in num}; maxLen = 0
for key in dict:
if dict[key] == False:
curr = key + 1; count = 1; dict[key] = True
while curr in dict and dict[curr] == False:
count += 1; dict[curr] = True; curr += 1
curr = key - 1;
while curr in dict and dict[curr] == False:
count += 1; dict[curr] = True; curr -= 1
maxLen = max(maxLen, count)
return maxLen