Skip to content

Commit 30a1246

Browse files
committed
128. Longest Consecutive Sequence
1 parent 116161f commit 30a1246

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+
const numSet = new Set(nums);
7+
let longestStreak = 0;
8+
9+
for (const num of numSet) {
10+
// ν˜„μž¬ μˆ«μžκ°€ 연속 μ‹œν€€μŠ€μ˜ μ‹œμž‘μ μΈμ§€ 확인
11+
// 즉, num-1이 set에 μ—†μ–΄μ•Ό 함
12+
if (!numSet.has(num - 1)) {
13+
let currentNum = num;
14+
let currentStreak = 1;
15+
16+
// ν˜„μž¬ 숫자의 μ—°μ†λœ λ‹€μŒ μˆ«μžλ“€μ„ 찾음
17+
while (numSet.has(currentNum + 1)) {
18+
currentNum += 1;
19+
currentStreak += 1;
20+
}
21+
22+
longestStreak = Math.max(longestStreak, currentStreak);
23+
}
24+
}
25+
26+
return longestStreak;
27+
};

0 commit comments

Comments
Β (0)