We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 59d4806 commit bcf2c8dCopy full SHA for bcf2c8d
longest-consecutive-sequence/samcho0608.java
@@ -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
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