- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem128.java
More file actions
Latest commit
28 lines (25 loc) · 872 Bytes
/
Copy pathProblem128.java
File metadata and controls
28 lines (25 loc) · 872 Bytes
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
importjava.util.Map;
importjava.util.HashMap;
classProblem128 {
publicstaticvoidmain(String[] args) {
int[] nums = {100, 4, 200, 1, 3, 2};
System.out.println(newProblem128().longestConsecutive(nums));
}
publicintlongestConsecutive(int[] nums) {
Map<Integer, Integer> map = newHashMap<>();
intmax = 0;
for(inti = 0; i < nums.length; i++) {
if (map.getOrDefault(nums[i], 0) == 0) { // 之前不存在该key
intleft = map.getOrDefault(nums[i]-1, 0);
intright = map.getOrDefault(nums[i]+1, 0);
map.put(nums[i], left + right + 1);
map.put(nums[i]-left, left+ right + 1);
map.put(nums[i]+right, left+right + 1);
max = max < (left+right + 1) ? left+right+1 : max;
} else {
map.put(nums[i], map.get(nums[i]));
}
}
returnmax;
}
}