-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestConsecutiveSequence.java
More file actions
39 lines (37 loc) · 1.03 KB
/
LongestConsecutiveSequence.java
File metadata and controls
39 lines (37 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.HashSet;
public class Solution {
public int longestConsecutive(int[] num) {
if(num == null) return -1;
if(num.length == 0) return 0;
int min = num[0];
int max = min;
HashSet<Integer> set = new HashSet<Integer>();
for(int i = 0; i < num.length; i++) {
int n = num[i];
set.add(n);
if(n > max) max = n;
if(n < min) min = n;
}
int maxLen = 1;
for(int i = 0; i < num.length; i++) {
int n = num[i];
set.remove(n);
int len = 1;
while(n < max) {
n++;
if(!set.contains(n)) break;
len++;
set.remove(n);
}
n = num[i];
while(n > min) {
n--;
if(!set.contains(n)) break;
len++;
set.remove(n);
}
if(len > maxLen) maxLen = len;
}
return maxLen;
}
}//O(n) O(n)