【leetcode】128. Longest Consecutive Sequence

题目如下:

解题思路:我的解法是先用字典dic记录所有在nums中出现的元素,一是为了后面方便查找,二是为了去重。接下来开始依次遍历nums中每个元素i,需要从前(即i+1)后(即i-1)两个方向查找,如果dic中存在i+1或者i-1,表示连续,接下来继续查找i+2,i-2,直到找到不存在的元素为止,记为i+k,i-j,那么这一段连续的长度就是k+j+1。注意:在查找的过程中,如果i+k,i-j在dic中存在,那么需要删除掉,这是为了避免重复查找,因为i+k,i-j已经包括在我们计算出来的这段序列中了。

代码如下:

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

      dic = {}
        for i in nums:
            if i not in dic:
                dic[i] = 1
        res = 0
        for i in nums:
            if i not in dic:
                continue
            count = 1
            high = i
            #分别往两个方向查找
            while True:
                if high + 1 in dic:
                    count += 1
                    #注意,存在的high+1的话,可以从dic中把这个元素删除,避免后面重复操作
                    dic.pop(high+1)
                else:
                    break
                high += 1
            low = i
            while True:
                if low - 1 in dic:
                    count += 1
                    dic.pop(low - 1)
                else:
                    break
                low -= 1
            #print i,count,res
            res = max(res,count)
        return res

 

posted @ 2018-05-10 10:42  seyjs  阅读(148)  评论(0编辑  收藏  举报