Skip to content

Commit 7900ad0

Browse files
committed
longest-consecutive-sequence solution
1 parent 1383091 commit 7900ad0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
// 시간복잡도: O(n)
7+
var longestConsecutive = function (nums) {
8+
let longest = 0;
9+
10+
let set = new Set(nums);
11+
12+
for (let num of nums) {
13+
if (set.has(num - 1)) {
14+
continue;
15+
}
16+
17+
let count = 1;
18+
let currentNum = num;
19+
20+
while (set.has(currentNum + 1)) {
21+
count++;
22+
currentNum++;
23+
}
24+
longest = Math.max(longest, count);
25+
}
26+
return longest;
27+
};
28+
29+
console.log(longestConsecutive([100, 4, 200, 1, 3, 2])); // 4
30+
console.log(longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])); // 9
31+
console.log(longestConsecutive([1, 0, 1, 2])); // 3

0 commit comments

Comments
 (0)