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
| class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { int n = nums.length; Map<Long, Long> map = new HashMap<>(); long size = t + 1L; for (int i = 0; i < n; ++i) { long u = nums[i]; long idx = getIdx(u, size); if (map.containsKey(idx)) return true; long l = idx - 1, r = idx + 1; if (map.containsKey(l) && u - map.get(l) <= t) return true; if (map.containsKey(r) && map.get(r) - u <= t) return true; map.put(idx, u); if (i >= k) map.remove(getIdx(nums[i - k], size)); } return false; }
private long getIdx(long u, long size) { return u >= 0 ? u / size : ((u + 1) / size) - 1; } }
|