Skip to content

Commit 66131a1

Browse files
committed
longest-consecutive-sequence solution
1 parent 75fe80b commit 66131a1

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+
/* 시간 복잡도: O(N)
5+
* - for 루프: O(N) O(N)
6+
* - HashSet(add, contains): O(1)
7+
*
8+
* 공간 복잡도: O(N), HashSet에 n개
9+
*/
10+
public int longestConsecutive(int[] nums) {
11+
Set<Integer> set = new HashSet<>();
12+
for (int num : nums) {
13+
set.add(num);
14+
}
15+
16+
int answer = 0;
17+
for (int num : set) {
18+
if (!set.contains(num - 1)) {
19+
int cur = num;
20+
int count = 1;
21+
while (set.contains(cur + 1)) {
22+
cur += 1;
23+
count += 1;
24+
}
25+
answer = Math.max(answer, count);
26+
}
27+
}
28+
29+
return answer;
30+
}
31+
}
32+

0 commit comments

Comments
 (0)