Skip to content

Commit 54cbbb5

Browse files
committed
longest consecutive sequence solution
1 parent 99aabb5 commit 54cbbb5

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function (nums) {
6+
// set์œผ๋กœ ์ค‘๋ณต๋œ element ์ œ๊ฑฐ
7+
const numSet = new Set(nums);
8+
// ์ตœ๋Œ€ ์—ฐ์† ๊ธธ์ด ๋ณ€์ˆ˜
9+
let maxLength = 0;
10+
11+
// ์ตœ๋Œ€ ์—ฐ์† ๊ธธ์ด ์ฐพ๊ธฐ
12+
for (let num of numSet) {
13+
// ๋งŒ์•ฝ ํ˜„์žฌ ์ˆ˜ -1์ด ์—†๋‹ค๋ฉด?
14+
if (!numSet.has(num - 1)) {
15+
let currentNum = num; //ํ˜„์žฌ๊ฐ’์ด ์‹œ์ž‘
16+
let currentLength = 1; //์ตœ๋Œ€ ๊ธธ์ด 1๋กœ ์ดˆ๊ธฐํ™”
17+
18+
// ํ˜„์žฌ๊ฐ’ +1์ด ์žˆ์„ ๋•Œ ๊นŒ์ง€ ๋ฐ˜๋ณต
19+
while (numSet.has(currentNum + 1)) {
20+
currentNum++;
21+
currentLength++;
22+
}
23+
24+
// ์ตœ๋Œ€๊ธธ์ด ๊ฐ’๊ณผ ํ˜„์žฌ ๊ธธ์ด๊ฐ’์ค‘ ๋” ๋†’์€๊ฒƒ์ด ์ตœ๋Œ€๊ธธ์ด๊ฐ’
25+
maxLength = Math.max(maxLength, currentLength);
26+
}
27+
}
28+
return maxLength;
29+
};

0 commit comments

Comments
ย (0)