Skip to content

Commit 4f0c3ba

Browse files
author
bhan
committed
longest consecutive sequence solution
1 parent a26c3ca commit 4f0c3ba

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function (nums) {
6+
if (nums.length === 0) return 0;
7+
8+
const numSet = new Set(nums);
9+
let longest = 0;
10+
for (let num of numSet) {
11+
// `num - 1`์ด ์—†์œผ๋ฉด ์ƒˆ๋กœ์šด ์ˆ˜์—ด์˜ ์‹œ์ž‘์ 
12+
if (!numSet.has(num - 1)) {
13+
let count = 1;
14+
let currentNum = num;
15+
16+
// ์—ฐ์†๋œ ์ˆซ์ž ์ฐพ๊ธฐ
17+
while (numSet.has(currentNum + 1)) {
18+
currentNum++;
19+
count++;
20+
}
21+
22+
longest = Math.max(longest, count);
23+
}
24+
}
25+
26+
return longest;
27+
};

0 commit comments

Comments
ย (0)