Skip to content

Commit e4613f7

Browse files
committed
Longest Consecutive Sequence
1 parent 9dced72 commit e4613f7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
Problem 128 : Longest Consecutive Sequence
3+
Summary :
4+
- for문으로 순회하면서, target에서 뺀 값을 저장한다.
5+
- 저장된 값과 일치하는 인덱스를 만나면 해당 값을 리턴한다.
6+
- 기본 For문이 O(N^2)이라면, 해당 방법의 경우 O(N)이 가능하다.
7+
8+
*/
9+
class Solution {
10+
public int longestConsecutive(int[] nums) {
11+
int max = 0;
12+
13+
Set<Integer> set = new HashSet<>();
14+
for(int num : nums) {
15+
set.add(num);
16+
}
17+
Set<Integer> completeSet = new HashSet<>();
18+
for(int i = 0; i < nums.length; i++) {
19+
if(!set.contains(nums[i]-1) && !completeSet.contains(nums[i])){
20+
int sequence = getSequence(nums[i], set);
21+
max= Math.max(sequence, max);
22+
completeSet.add(nums[i]);
23+
}
24+
}
25+
26+
return max;
27+
28+
29+
}
30+
31+
public int getSequence(int startNum, Set<Integer> numSet) {
32+
int result = 1;
33+
while(true) {
34+
startNum++;
35+
if(!numSet.contains(startNum)) {
36+
break;
37+
}
38+
result++;
39+
}
40+
return result;
41+
}
42+
}

0 commit comments

Comments
 (0)