码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]124. Longest Consecutive Sequence/[Leetcode]128. Longest Consecutive Sequence

时间:2019-02-17 15:31:49      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:更新   href   lintcode   stc   .com   python   har   def   cep   

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

标签:更新   href   lintcode   stc   .com   python   har   def   cep   

原文地址:https://www.cnblogs.com/siriusli/p/10388011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!