-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution220.java
37 lines (31 loc) · 1.07 KB
/
Solution220.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
package algorithm.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* @author: mayuan
* @desc: 存在重复元素 III
* @date: 2019/03/02
*/
public class Solution220 {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
if (k < 1 || t < 0) {
return false;
}
Map<Long, Long> map = new HashMap<>(k);
for (int i = 0; i < nums.length; ++i) {
long remappedNum = (long) nums[i] - Integer.MIN_VALUE;
long bucket = remappedNum / ((long) t + 1);
if (map.containsKey(bucket)
|| (map.containsKey(bucket - 1) && remappedNum - map.get(bucket - 1) <= t)
|| (map.containsKey(bucket + 1) && map.get(bucket + 1) - remappedNum <= t)) {
return true;
}
if (map.size() >= k) {
long lastBucket = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
map.remove(lastBucket);
}
map.put(bucket, remappedNum);
}
return false;
}
}