-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLongestConsecutiveSequence.java
66 lines (59 loc) · 1.61 KB
/
LongestConsecutiveSequence.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
60
61
62
63
64
65
66
public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] nums) {
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);
}
int longest = 0;
for (int i = 0; i < nums.length; i++) {
int down = nums[i] - 1;
while (set.contains(down)) {
set.remove(down);
down--;
}
int up = nums[i] + 1;
while (set.contains(up)) {
set.remove(up);
up++;
}
longest = Math.max(longest, up - down - 1);
}
return longest;
}
}
// version: 高频题班
public class Solution {
/**
* @param nums: A list of integers
* @return an integer
*/
public int longestConsecutive(int[] num) {
// write you code here
Set<Integer> set = new HashSet<>();
for (int item : num) {
set.add(item);
}
int ans = 0;
for (int item : num) {
if (set.contains(item)) {
set.remove(item);
int l = item - 1;
int r = item + 1;
while (set.contains(l)) {
set.remove(l);
l--;
}
while (set.contains(r)) {
set.remove(r);
r++;
}
ans = Math.max(ans, r - l - 1);
}
}
return ans;
}
}