2
* Sliding Window solution using Buckets4
* <p>Time Complexity: O(N)6
* <p>Space Complexity: O(min(N, K+1))8
* <p>N = Length of input array. K = Input difference between indexes.11
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {12
if (nums == null || nums.length < 2 || k < 1 || t < 0) {16
HashMap<Long, Long> buckets = new HashMap<>();17
// The bucket size is t+1 as the ranges are from 0..t, t+1..2t+1, ..18
long bucketSize = (long) t + 1;20
for (int i = 0; i < nums.length; i++) {21
// Making sure only K buckets exists in map.23
long lastBucket = ((long) nums[i - k - 1] - Integer.MIN_VALUE) / bucketSize;24
buckets.remove(lastBucket);27
long remappedNum = (long) nums[i] - Integer.MIN_VALUE;28
long bucket = remappedNum / bucketSize;30
// If 2 numbers belong to same bucket31
if (buckets.containsKey(bucket)) {35
// If numbers are in adjacent buckets and the difference between them is at most37
if (buckets.containsKey(bucket - 1) && remappedNum - buckets.get(bucket - 1) <= t) {40
if (buckets.containsKey(bucket + 1) && buckets.get(bucket + 1) - remappedNum <= t) {44
buckets.put(bucket, remappedNum);