Skip to content

Commit a95ca38

Browse files
longest consecutive sequence solution
1 parent 7c4ce77 commit a95ca38

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
class SolutionLongestConsecutiveSequence {
5+
6+
public int longestConsecutive(int[] nums) {
7+
// 정렬되지 않은 정수 nums 배열이 주어지면 가장 긴 연속 요소 시퀀스 길이를 반환
8+
// O(N) 시간 내 실행되야함
9+
// 전부 해시맵에 때려넣고, 키를 꺼내 연속 요소가 있는지 확인한다
10+
// 연속 요소가 있으면 answer를 1 증가시키고, 연속 요소는 제거한다
11+
// 시간복잡도: O(N), 공간복잡도: O(N)
12+
13+
Set<Integer> set = new HashSet<>();
14+
for (var num : nums) {
15+
set.add(num);
16+
}
17+
var answer = 0;
18+
for (var num : nums) {
19+
var length = 1;
20+
21+
if (set.contains(num-1)) {
22+
set.remove(num);
23+
var minusKey = num;
24+
while (set.contains(--minusKey)) {
25+
length++;
26+
set.remove(minusKey);
27+
}
28+
}
29+
30+
if (set.contains(num+1)) {
31+
set.remove(num);
32+
var plusKey = num;
33+
while (set.contains(++plusKey)) {
34+
length++;
35+
set.remove(plusKey);
36+
}
37+
}
38+
39+
if (length > answer) {
40+
answer = length;
41+
}
42+
}
43+
44+
return answer;
45+
}
46+
}

0 commit comments

Comments
 (0)