Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
题意找到一组数,nums[i] and nums[j] 他们idx差值在k之内, 即 j - i <= k. 他们的差的绝对值在t之内,即 Math.abs(nums[i] - nums[j]) <= t. 咱们能够构建一个大小为t+1的bucket, 好比[0, 1, 2, 3, ... , t] 最大绝对值差的两个数就是t和0. 若是两个数字出如今同一个Bucket内,说明咱们已经找到了。 若是不是,则在相邻的两个bucket内再找。 若是相邻的bucket内元素绝对值只差在t之内,说明咱们知道到了,返回true. 为了保证j - i <= k,咱们在i>=k时,删除 nums[i-k]对应的Bucket.
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if( k < 1 || t < 0) return false; Map<Long, Long> map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ // [-t, 0] [0, t] 的元素都会落在bucket[0]里。 // 为了解决这个问题,全部元素横移Integer.MIN_VALUE。 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(i >= k) { long lastBucket = ((long) nums[i-k] - Integer.MIN_VALUE) / ((long)t + 1); map.remove(lastBucket); } map.put(bucket,remappedNum); } return false; } }
TreeSet也能够解决这个问题, 咱们首先须要把i-j <=k 的全部元素装起来, 而后集合内的元素能够保证有序,在里面找最接近nums[i] +/- t的元素就好了。 [11,12,14,15] tree.floor(13) = 12 tree.floor(12) = 12 tree.ceiling(13) = 14 tree.ceiling(14) = 14
public class Solution { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { if( k < 1 || t < 0) return false; TreeSet<Long> tree = new TreeSet<>(); for(int i = 0; i < nums.length; i++){ Long floor = tree.floor((long)nums[i] + t); Long ceil = tree.ceiling((long)nums[i] - t); if((floor != null && floor >= nums[i]) || (ceil != null && ceil <= nums[i]) ) return true; tree.add((long)nums[i]); if(i >= k){ tree.remove((long)nums[i-k]); } } return false; } }