Skip to content

Commit bcf2c8d

Browse files
committed
solve longest consecutive sequence
1 parent 59d4806 commit bcf2c8d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
class Solution {
5+
// * nums is unsorted
6+
// * return: length of longest consecutive elements sequence
7+
// * req: O(N) time
8+
public int longestConsecutive(int[] nums) {
9+
Set<Integer> uniq = new HashSet<>();
10+
11+
// O(N)
12+
for(int num : nums) {
13+
uniq.add(num);
14+
}
15+
16+
// O(N)
17+
int maxLen = 0;
18+
for(int num : uniq) {
19+
// 기존에 시작된 consecutive sequence가 있으면 스킵
20+
if(uniq.contains(num - 1)) continue;
21+
22+
// count till end of consecutive sequence
23+
int len = 1;
24+
for(int i = 1; uniq.contains(num + i); i++) {
25+
len++;
26+
}
27+
28+
maxLen = Math.max(maxLen, len);
29+
}
30+
31+
return maxLen;
32+
}
33+
}

0 commit comments

Comments
 (0)