最长连续序列

https://leetcode-cn.com/problems/longest-consecutive-sequence/submissions/

最长序列最开始想到的解法是先排序然后再遍历,这样的时间复杂度nlogn不符合题目要求
所以需要用空间换时间 用hash table来存放每个数据
然后遍历一遍,找left和right,如果在table里面则➕1,然后删除该键(减少重复计算), 最后和max-length来比较得到max-length

class Solution(object):
    def longestConsecutive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        max_length = 0
        cache = {}
        for i in nums:
            cache[i] = 1
        
        for n in nums:
            current_length = 1
            if n not in cache:
                continue
            left = n - 1
            right = n + 1
            while left in cache:
                cache.pop(left)
                current_length += 1
                left = left - 1
            while right in cache:
                cache.pop(right)
                current_length += 1
                right += 1
            max_length = max(max_length, current_length)
        return max_length


你可能感兴趣的:(最长连续序列)