LeetCode 128. 最长连续序列

题目描述

128. 最长连续序列

image-20250419071506439

思路分析

哈希集合法

image-20250510112214503

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func longestConsecutive(nums []int) int {
	numSet := make(map[int]bool)
	for _, num := range nums {
		numSet[num] = true
	}
	maxLen := 0
	for num := range numSet {
		// 只从序列的起始点开始查找
		if _, exists := numSet[num-1]; !exists {
			curNum := num
			curLen := 1
			// 向上查找连续的数字
			for {
				if _, exists := numSet[curNum+1]; exists {
					curNum++
					curLen++
				} else {
					break
				}
			}
			maxLen = max(maxLen, curLen)
		}
	}
	return maxLen
}
  • 时间复杂度:O(n),其中 n 是数组 nums 的长度。
  • 空间复杂度:O(n),需要一个哈希集合来存储所有数字。

➡️ 点击查看 Java 题解

1
write your code here
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/54759261
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!