Skip to content

Commit bd65038

Browse files
committed
longest consecutive sequence solution
1 parent 63f4483 commit bd65038

File tree

1 file changed

+30
-0
lines changed

1 file changed

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

0 commit comments

Comments
ย (0)