[Leetcode]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.

给定一个未排序的数组,找到最长的连续整数序列~要求复杂度为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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值