L|

题目描述

🔥 128. 最长连续序列

思路分析

这个问题的关键在于如何在 O(n) 时间内找到最长连续序列。我们可以使用 HashSet 来实现这一目标,具体思路如下:

  1. 创建一个 HashSet,将数组中的所有元素存储到 HashSet 中。
  2. 遍历数组中的每个元素,对于每个元素 num,判断 num - 1 是否存在于 HashSet 中。如果不存在,说明 num 是一个连续序列的起点。
  3. 对于每个连续序列的起点 num,开始递增 num,同时检查 num + 1 是否存在于 HashSet 中,以此来扩展连续序列的长度。
  4. 在遍历过程中,不断更新最长连续序列的长度。
  5. 返回最长连续序列的长度作为结果。

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func longestConsecutive(nums []int) int {
	numSet := make(map[int]bool)
	for _, num := range nums {
		numSet[num] = true
	}
	maxLength := 0
	for num := range numSet {
		if !numSet[num-1] { // 如果 num 是序列的起点
			curNum := num
			curLength := 1
			// 依次检查序列中的下一个数字
			for numSet[curNum+1] {
				curNum++
				curLength++
			}
			// 更新最大长度
			if curLength > maxLength {
				maxLength = curLength
			}
		}
	}
	return maxLength
}

🍏 点击查看 Java 题解

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