Skip to content

Commit d2a625b

Browse files
committed
add solution: longest-consecutive-sequence
1 parent 114f833 commit d2a625b

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+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
2+
3+
/**
4+
* @param {number[]} nums
5+
* @return {number}
6+
*/
7+
var longestConsecutive = function (nums) {
8+
// Set์„ ์‚ฌ์šฉํ•ด ์ค‘๋ณต ์ œ๊ฑฐ
9+
const numSet = new Set(nums);
10+
let longestStreak = 0;
11+
12+
// ๊ฐ ์ˆซ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์—ฐ์† ์‹œํ€€์Šค๋ฅผ ํƒ์ƒ‰
13+
for (let num of numSet) {
14+
// num์ด ์‹œํ€€์Šค์˜ ์‹œ์ž‘์ ์ธ ๊ฒฝ์šฐ๋งŒ ํƒ์ƒ‰
15+
if (!numSet.has(num - 1)) {
16+
let currentNum = num;
17+
let currentStreak = 1;
18+
19+
// ํ˜„์žฌ ์‹œํ€€์Šค๋ฅผ ๋”ฐ๋ผ๊ฐ€๋ฉฐ ๊ธธ์ด ๊ณ„์‚ฐ
20+
while (numSet.has(currentNum + 1)) {
21+
currentNum++;
22+
currentStreak++;
23+
}
24+
25+
// ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ์—…๋ฐ์ดํŠธ
26+
longestStreak = Math.max(longestStreak, currentStreak);
27+
}
28+
}
29+
30+
return longestStreak;
31+
};

0 commit comments

Comments
ย (0)