Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
58 lines (55 loc) · 1.72 KB

File metadata and controls

58 lines (55 loc) · 1.72 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package LeetCode.array;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class LeetCode128 {
public int longestConsecutive(int[] nums) {
if(nums == null || nums.length == 0) return 0;
Map<Integer, Integer> map = new HashMap<>();
int max = 0;
for(int num : nums){
if (map.containsKey(num)) continue;
Integer leftLn = map.get(num-1);
Integer rightLn = map.get(num+1);
int ln = 1;
if (leftLn != null && rightLn != null) {
ln = leftLn+rightLn+1;
map.replace(num-leftLn, ln);
map.replace(num+rightLn, ln);
map.put(num, ln);
}
else if(leftLn != null) {
ln = leftLn+1;
map.replace(num-leftLn, ln);
map.put(num, ln);
}
else if (rightLn != null){
ln = rightLn+1;
map.replace(num+rightLn, ln);
map.put(num, ln);
}
else {
map.put(num, ln);
}
max = Math.max(max, ln);
}
return max;
}
//=========================
public int longestConsecutive2(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums){
set.add(num);
}
int max = 0;
for(int num : nums) {
if (!set.remove(num)) continue;
int lt = num-1, rt = num+1;
while (set.remove(lt)) lt--;
while (set.remove(rt)) rt++;
max = Math.max(max, rt-lt-1);
}
return max;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.