Skip to content

Commit 20ee1a6

Browse files
committed
longest consecutive sequence solution
1 parent 1b4635e commit 20ee1a6

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
const longestConsecutive = (nums) => {
6+
if (nums.length === 0) return 0;
7+
8+
const numSet = new Set(nums);
9+
let maxLength = 0;
10+
11+
for (const num of numSet) {
12+
// ์‹œํ€€์Šค ์‹œ์ž‘์ ๋งŒ ์ฒดํฌ
13+
if (!numSet.has(num - 1)) {
14+
let currentNum = num;
15+
let currentLength = 1;
16+
17+
// ์—ฐ์†๋œ ์ˆซ์ž ์นด์šดํŠธ
18+
while (numSet.has(currentNum + 1)) {
19+
currentNum++;
20+
currentLength++;
21+
}
22+
23+
maxLength = Math.max(maxLength, currentLength);
24+
}
25+
}
26+
27+
return maxLength;
28+
};

0 commit comments

Comments
ย (0)