128 Longest Consecutive Sequence

这道题一开始无从下手,想到找到用hashtable,这样查询没个数是否在List中只需要O(1)时间。 

以上是第一步, 接下来的想法就比较自然, 将每个数都当成可能的起始点进行测试。待测试的起始点为n,如果n-1在set中,则n必不为起始数字,可以continue优化运行时间

代码中使用set来实现hashtable的作用, 需要O(n)时间。 每一次查询 最多需要O(k)时间, 

总复杂度即为O(n)+O(k) = O(n)

class Solution:
    # @param {integer[]} nums
    # @return {integer}
    def longestConsecutive(self, nums):
        nums = set(nums)
        ans = 0
        for n in nums:
            if n-1 in nums:
                continue
            else:
                tmpN = n
                tmpL = 0
                while tmpN in nums:
                    tmpL += 1
                    tmpN += 1
                ans = max(ans, tmpL)
        return ans

 

posted @ 2015-07-07 10:36  dapanshe  阅读(125)  评论(0编辑  收藏  举报