Skip to content

Commit 61bb104

Browse files
author
이호찬
committed
longest-consecutive-sequence solution
1 parent db0e1ea commit 61bb104

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+
var longestConsecutive = function(nums) {
6+
const numSet = new Set(nums);
7+
8+
let maxLength = 0;
9+
let currentLength = 0;
10+
11+
nums.forEach(num => {
12+
let currentNum = num;
13+
while(numSet.has(currentNum)) {
14+
numSet.delete(currentNum)
15+
currentNum += 1;
16+
currentLength += 1;
17+
}
18+
19+
currentNum = num - 1;
20+
while(numSet.has(currentNum)) {
21+
numSet.delete(currentNum)
22+
currentNum -= 1;
23+
currentLength += 1;
24+
}
25+
26+
maxLength = Math.max(maxLength, currentLength);
27+
currentLength = 0;
28+
});
29+
30+
return maxLength;
31+
};

0 commit comments

Comments
 (0)