Longest Consecutive Sequence
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。
Nov, 9, 2017.
https://leetcode.com/problemset/algorithms/?topicSlugs=union-find%2Clinked-list
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),以下是submission。
1 class Solution: 2 def longestConsecutive(self, nums): 3 length = {} 4 ans = 0 5 for i in nums: 6 if i not in length: 7 l = length[i - 1] if i - 1 in length else 0 8 r = length[i + 1] if i + 1 in length else 0 9 length[i] = length[i - l] = length[i + r] = l + r + 1 10 ans = max(ans, length[i]) 11 return ans
解法二,数组->哈希表,寻找连续序列起始数(x-1 not in nums),直接查找这个序列的长度。
有趣的地方在于,我们是在哈希表里查询一个确定的数,使得这个操作的复杂度被压进了O(1)。因此这个算法的复杂度还是O(N)。
以下是StefanPochmann的submission。
1 def longestConsecutive(self, nums): 2 nums = set(nums) 3 best = 0 4 for x in nums: 5 if x - 1 not in nums: 6 y = x + 1 7 while y in nums: 8 y += 1 9 best = max(best, y - x) 10 return best
其实两种方法都利用了哈希表查询的便利性。我原来想把输入看作森林,用并查集来完成工作。这种算法不好实现,也不见得简单。
以上是关于Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章
LC.298.Binary Tree Longest Consecutive Sequence