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)