LeetCode-128、 最长连续序列-困难

LeetCode-128、 最长连续序列-困难

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)

示例:

输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。

代码:

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        hashdict = {}
        maxlen = 0
        for n in nums:
            if n in hashdict:
                continue
            left = hashdict.get(n-1, 0)
            right = hashdict.get(n+1, 0)
            hashdict[n] = left + right + 1
            maxlen = max(maxlen, hashdict[n])
            hashdict[n-left] = hashdict[n]
            hashdict[n+right] = hashdict[n]
        return maxlen

发布了209 篇原创文章 · 获赞 48 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/clover_my/article/details/104685989