Longest Consecutive Sequence
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.
这是一道拿在手上不知道怎么下手的题目,题目tag提示是并查集,但是感觉和传统的并查集合并思路差别很大.参考了discussion里面的一个解决思路,主要是应用hashmap记录每个元素所属连续区间的长度,每次更新现有区间的两边节点的value为当前序列的长度.代码如下:
class Solution(object): def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ #how to use the union-find how to union #smallest,largest element hash = {} res = 0 for i in nums: if i not in hash: #防止重复 left = hash[i-1] if i-1 in hash else 0 #获取左边部分的长度 right = hash[i+1] if i+1 in hash else 0 #获取右边部分的长度 total = left + right + 1 hash[i] = total res = max(res, total) #更新最长长度 hash[i-left] = total #更新边缘点的长度,非常关键,方便之后的合并 hash[i + right] = total #更新边缘点的长度,非常关键,方便之后的合并 return res
posted on 2016-09-01 15:45 Sheryl Wang 阅读(139) 评论(0) 编辑 收藏 举报