Skip to content

Commit 1b3d9a0

Browse files
committed
feat: 128. Longest Consecutive Sequence
1 parent 11b4bc5 commit 1b3d9a0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @return {number}
7+
*/
8+
var longestConsecutive = function (nums) {
9+
let answer = 0;
10+
const consecutiveDict = new Map();
11+
12+
for (const num of nums) {
13+
consecutiveDict.set(num, true);
14+
}
15+
16+
for (const num of nums) {
17+
if (consecutiveDict.has(num - 1)) {
18+
continue;
19+
}
20+
21+
let length = 1;
22+
while (consecutiveDict.has(num + length)) {
23+
length++;
24+
}
25+
26+
answer = Math.max(answer, length);
27+
}
28+
29+
return answer;
30+
};

0 commit comments

Comments
 (0)