[Lintcode]124. Longest Consecutive Sequence/[Leetcode]128. Longest Consecutive Sequence
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]124. Longest Consecutive Sequence/[Leetcode]128. Longest Consecutive Sequence相关的知识,希望对你有一定的参考价值。
124. Longest Consecutive Sequence/128. Longest Consecutive Sequence
- 本题难度: Medium/Hard
- Topic: Data Structure
Description
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Example
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Clarification
Your algorithm should run in O(n) complexity.
```
我的代码
class Solution:
"""
@param num: A list of integers
@return: An integer
"""
def longestConsecutive(self, num):
# write your code here
dic = dict()
res = 0
for item in num:
if dic.get(item, 0)==0:
left = dic.get(item - 1, 0)
right = dic.get(item + 1, 0)
new = left + right + 1
if new>res:
res = new
dic[item] = dic[item - left] = dic[item + right] = new
return res
思路
因为需要时间复杂度为O(n),所以不能用排序做。
查找肯定不能用list,要用set或者dictionary这种hash table实现的情况。
可以扫描有限次。
没什么思路。
Leetcode分到了,Union Find。
查集(Union-Find Algorithm)
看了一下Leetcode的discussion: My really simple Java O(n) solution - Accepted
[100, 4, 200, 1, 3, 2]
New hash table []
for num in nums:
if num in hash table: continue
get left #右边靠近n的连续子列(left-left_sum,left),不存在时设为0
get right #左边靠近n的连续子列(right,right+right_sum),不存在时设为0
key(n) = key(left)+key(right)+1
形成一个新的连续子列,(n-left_sum,n+right_sum),它们新的sum为key(n)
之后的num只可能在这个子列之外,所以子列中的key无需更新。
Example
[100, 4, 200, 1, 3, 2]
# 100
[100,1]
# 4
[100,1] [4,1]
#200
[100,1] [200,1] [4,1]
# 1
[100,1] [200,1] [4,1] [1,1]
#3
[100,1] [200,1] [4,2] [3,2] [1,1]
#2
[100,1] [200,1] [4,3] [3,2] [2,3] [1,3]
- 时间复杂度 O(n) (使用hash table降低了复杂度)
- 空间复杂度 O(n)
以上是关于[Lintcode]124. Longest Consecutive Sequence/[Leetcode]128. Longest Consecutive Sequence的主要内容,如果未能解决你的问题,请参考以下文章
LintCode Longest Common Substring
lintcode-medium-Longest Increasing Subsequence
lintcode-medium-Longest Consecutive Sequence