LeetCode 128. 最长连续序列
题目描述
思路分析
哈希集合法
参考代码
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),需要一个哈希集合来存储所有数字。
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用