-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsecutiveSequenceFinder.java
59 lines (46 loc) · 1.26 KB
/
ConsecutiveSequenceFinder.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
package org.sean.array;
import java.util.HashSet;
import java.util.Set;
// 128. Longest Consecutive Sequence
public class ConsecutiveSequenceFinder {
private int maxLen = 0;
private Set<Integer> set = new HashSet<>();
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
set.clear();
int size = nums.length;
for (int n : nums) {
set.add(n);
}
int cnt = 0;
int elem;
int preKey;
int postKey;
for (int i = 0; i < size; i++) {
cnt = 0;
elem = nums[i];
if (set.contains(elem)) {
++cnt;
set.remove(elem);
preKey = elem - 1;
postKey = elem + 1;
while (set.contains(preKey)) {
set.remove(preKey);
preKey--;
++cnt;
}
while (set.contains(postKey)) {
set.remove(postKey);
postKey++;
++cnt;
}
if (cnt > maxLen) {
maxLen = cnt;
}
}
}
return maxLen;
}
}