vault backup: 2026-05-13 12:05:09

This commit is contained in:
2026-05-13 12:05:09 +08:00
parent 50aed8f968
commit bdc05d1a19
+4 -4
View File
@@ -61,7 +61,7 @@ create time: 2026-05-13 14:30
```mermaid
flowchart TD
A["将 nums 全部放入哈希集合 s"] --> B["遍历每个数 num"]
A["将 nums 全部放入哈希集合 s"] --> B["遍历集合 s 中的每个数 num"]
B --> C{"num - 1 在 s 中?"}
C -->|"是"| D["不是起点, 跳过"]
C -->|"否"| E["从 num+1 开始, 不断 +1 检查是否在 s 中"]
@@ -76,7 +76,7 @@ flowchart TD
#### 为什么仍是 O(n)?
- **建集合**:O(n)
- **外层遍历**:n 次迭代
- **外层遍历**:遍历 set 的 key,最多 n 次迭代(重复元素已被去重,不会产生多余循环)
- **内层 while 展开**:每个元素最多被内层访问一次——因为只有它是起点时才会进入 while,而一旦某个数被 while 访问过,后续任何枚举到它时都必然有 `num-1` 也在集合中,不会再次展开。
两个循环加起来,每个元素的总访问次数是常数次,因此整体 O(n)。
@@ -109,7 +109,7 @@ flowchart TD
set = 将 nums 所有元素放入哈希集合
ans = 0
for each num in nums:
for each num in set:
if (num - 1) NOT in set:
// num 是某个连续序列的起点
current = num + 1
@@ -174,7 +174,7 @@ func longestConsecutive(nums []int) int {
}
ans := 0
for _, num := range nums {
for num := range set {
// 只有 num-1 不在集合中时,num 才是连续序列的起点
if _, ok := set[num-1]; !ok {
current := num + 1