LeetCode #128:最长连续序列
1970-01-01 00:00 (GMT+8) 阅读时间 0 分钟 面试算法LeetCodeLeetCode-MediumPython哈希表并查集数组
https://leetcode.cn/problems/longest-consecutive-sequence/description/
题目分析
先把模板套上,求最长和最大问题,一般就是先维护一个当前值 current
,一个最大值 max
,然后用 max(current, max)
来更新最大值。又因为这题要求
又因为如果一个元素
题解
注意循环是在去重集合中循环,而不是在原数组中循环。原数组中可能有大量重复的数,第一遍我就是这样 TLE 的。
python
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
longest =0
current_num = 0
current = 0
dedup = set(nums)
for num in dedup:
if not num - 1 in dedup:
current_num = num
current = 1
while current_num + 1 in dedup:
current_num += 1
current += 1
longest = max(longest, current)
return longest