原题
https://leetcode.cn/problems/longest-consecutive-sequence/description/
思路
集合
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
# 将数组转为集合
s = set(nums)
ans = 0
for n in s:
if n - 1 in s:
# n不是连续数组的起点
continue
next = n + 1
count = 1
while next in s:
count += 1
next += 1
ans = max(ans, count)
return ans
Go代码
func longestConsecutive(nums []int) int {
// 将数组转为集合
set := make(map[int]bool)
for _, n := range nums {
set[n] = true
}
ans := 0
// 遍历集合
for n := range set {
if set[n-1] {
// n不是连续数组的起点
continue
}
next := n + 1
count := 1
for set[next] {
count++
next++
}
ans = max(ans, count)
}
return ans
}
828

被折叠的 条评论
为什么被折叠?



