Skip to content

Commit c4f4785

Browse files
committed
feat: solve longest-consecutive-sequence
1 parent 9381f46 commit c4f4785

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import java.util.*;
2+
import java.util.stream.Collectors;
3+
4+
class Solution {
5+
public int longestConsecutive(int[] nums) {
6+
Set<Integer> set = Arrays.stream(nums).boxed().collect(Collectors.toSet());
7+
8+
int maxLength = 0;
9+
for (int num: nums) {
10+
// 각 숫자에 대해 최초 값이 가능하면, 즉 num-1이 존재하지 않으면 최대 length 구하기
11+
if (set.contains(num - 1)) continue;
12+
int length = 1;
13+
int start = num;
14+
while (set.contains(start + 1)) {
15+
length++;
16+
start++;
17+
}
18+
maxLength = Math.max(length, maxLength);
19+
}
20+
21+
return maxLength;
22+
}
23+
}

0 commit comments

Comments
 (0)