-
Notifications
You must be signed in to change notification settings - Fork 1
/
maxConsecNum.java
59 lines (46 loc) · 1.38 KB
/
maxConsecNum.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// leetcode Longest Consecutive Sequence
import java.util.*;
import java.lang.Integer;
public class maxConsecNum {
public static void main(String args[]) {
int arr[] = {1,0,-1};
Solution cl = new Solution();
System.out.println(cl.longestConsecutive(arr));
}
}
class Solution {
public int longestConsecutive(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
HashSet<Integer> set = new HashSet<Integer>();
for (int i : num)
set.add(i);
int start, end;
int count = 0;
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
int n = it.next();
int tmp = n;
set.remove(n);
start = n;
end = n;
//System.out.println("n: " + n);
while (set.contains(n + 1)) {
set.remove(n + 1);
n++;
end = end + 1;
}
n = tmp;
while (set.contains(n - 1)) {
set.remove(n - 1);
n--;
start = start - 1;
}
if (end - start + 1 > count)
count = end - start + 1;
//System.out.println("start: " + start + "end: " + end);
it = set.iterator();
}
return count;
}
}