Skip to content

Commit 8fa725f

Browse files
committed
最长连续序列, set解法
1 parent 1992b05 commit 8fa725f

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

128.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* @lc app=leetcode.cn id=128 lang=typescript
3+
*
4+
* [128] 最长连续序列
5+
*/
6+
7+
// @lc code=start
8+
function longestConsecutive(nums: number[]): number {
9+
if (nums.length === 0) {
10+
return 0
11+
}
12+
13+
const numSet = new Set(nums)
14+
let max = 1
15+
for (let num of numSet) {
16+
if (numSet.has(num - 1)) {
17+
continue
18+
}
19+
let cur = 1
20+
let curNum = num
21+
while (numSet.has(curNum + 1)) {
22+
cur++
23+
curNum++
24+
}
25+
max = Math.max(cur, max)
26+
}
27+
return max
28+
};
29+
// @lc code=end
30+
31+
console.log(longestConsecutive([100, 4, 200, 1, 3, 2]))

0 commit comments

Comments
 (0)