220. Contains Duplicate III

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;
    }
}
相關文章
相關標籤/搜索