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.

 

找出数组中有没有最多相距k,同时最大相差t的两个数。
 
1、第一次超时,用了很笨的办法,放入ArrayList中,但是由于特殊点,要用Long类型,然后每一次都需要排序,所以果断超时了。
public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (t < 0 || k < 1){
            return false;
        }
        if (k > nums.length - 1){
            k = nums.length - 1;
        }
        ArrayList<Long> list = new ArrayList();
        for (int i = 0; i <= k; i++){
            list.add((long)nums[i]);
        }
        Collections.sort(list);
        for (int i = 1; i < list.size(); i++){
            if (list.get(i) - list.get(i - 1) <= t){
                return true;
            }
        }
        for (int i = k + 1; i < nums.length; i++){
            list.remove((long)nums[i - k - 1]);
            list.add((long)nums[i]);
            Collections.sort(list);
            for (int j = 1; j < list.size(); j++){
                if (list.get(j) - list.get(j - 1) <= t){
                    return true;
                }
            }
        }
        return false;
    }
}

 

2、用map实现,类似于桶排序的原理,首先把数据都转成正数,并且使用long型(否则会出错,比如-2和2除以3都等于0,但是相距4大于3),同时桶(t) = t + 1(t == 0的情况要排出)

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if (k < 1 || t < 0){
            return false;
        }
        HashMap<Long, Long> map = new HashMap();
        for (int i = 0; i < nums.length; i++){
            
            long pos = (long) nums[i] - Integer.MIN_VALUE;
            long num = pos / ((long) t + 1);
            if (map.containsKey(num) || (map.containsKey(num - 1) && Math.abs(map.get(num - 1) - pos) <= t) 
                                     || (map.containsKey(num + 1) && Math.abs(map.get(num + 1) - pos) <= t)){
                return true;
            }
            if (map.size() >= k){
                long delete = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
                map.remove(delete);
            }
            map.put(num, pos);
        }
        return false;
    }
}