Skip to content

Commit 34cef64

Browse files
committed
feat: add question 128
1 parent 99c6a00 commit 34cef64

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

128.data

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
[0,3,7,2,5,8,4,6,0,1]

128.最长连续序列.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* @lc app=leetcode.cn id=128 lang=javascript
3+
*
4+
* [128] 最长连续序列
5+
*
6+
* 1. 存储每个点的最左端和最右端
7+
* 2. 新增点时, 判断左端是否存在, 存在则当前点的最左端为左端点的最左端, 右端点同理
8+
* 3. 新的点插入后, 更新该点所在的最左端点的最右端值, 和最右端点的最左端值
9+
* 4. 取每次最左和最右端点距离中的最大值
10+
*/
11+
12+
// @lc code=start
13+
/**
14+
* @param {number[]} nums
15+
* @return {number}
16+
*/
17+
var longestConsecutive = function(nums) {
18+
const map = {};
19+
let result = 0;
20+
21+
for (const n of nums) {
22+
if (map[n]) {
23+
continue;
24+
}
25+
map[n] = {};
26+
27+
if (map[n - 1]) {
28+
map[n].left = map[n - 1].left;
29+
} else {
30+
map[n].left = n;
31+
}
32+
33+
if (map[n + 1]) {
34+
map[n].right = map[n + 1].right;
35+
} else {
36+
map[n].right = n;
37+
}
38+
39+
map[map[n].left].right = map[n].right;
40+
map[map[n].right].left = map[n].left;
41+
42+
result = Math.max(result, map[n].right - map[n].left + 1);
43+
}
44+
45+
return result;
46+
};
47+
// @lc code=end
48+

0 commit comments

Comments
 (0)