Skip to content

Commit ff2f605

Browse files
committed
🎨 Longest Consecutive Sequence Solution
1 parent d9d6dbc commit ff2f605

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
public int longestConsecutive(int[] nums) {
5+
Set<Integer> numSet = new HashSet<>();
6+
for (int num : nums) {
7+
numSet.add(num);
8+
}
9+
10+
int longNum = 0;
11+
12+
// 각 μˆ«μžμ— λŒ€ν•΄ μ‹œν€€μŠ€ μ‹œμž‘ μ—¬λΆ€λ₯Ό 확인
13+
for (int num : numSet) {
14+
// num-1이 μ—†λŠ” κ²½μš°μ—λ§Œ μ‹œν€€μŠ€λ₯Ό μ‹œμž‘
15+
if (!numSet.contains(num - 1)) {
16+
int currentNum = num;
17+
int currentLong = 1;
18+
19+
// μ—°μ†λœ 숫자λ₯Ό 탐색
20+
while (numSet.contains(currentNum + 1)) {
21+
currentNum++;
22+
currentLong++;
23+
}
24+
25+
// κ°€μž₯ κΈ΄ μ‹œν€€μŠ€λ₯Ό κ°±μ‹ 
26+
longNum = Math.max(longNum, currentLong);
27+
}
28+
}
29+
30+
return longNum;
31+
}
32+
}

0 commit comments

Comments
Β (0)