#leetcode#Contains Duplicates III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] andnums[j] is at most t and the difference between i and j is at most k.


利用TreeSet的floor()和ceiling()method,分别可以得到greatest value that is less than current value, 和 least value that is greater than current value, 即可以找到当前set中的差值(current - floor 或者 ceiling - current)

注意这里有可能会Integer Overflow, 所以用了long来转换一下

还有就是TreeSet的size需要维持在k上, 加入新元素时要把最左边元素删掉


时间复杂度需要考虑  TreeSet的操作都是logn的, 然后TreeMap的size是K, 所以时间复杂度是O(nlogk)

public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        if(nums == null || nums.length < 2 || k <= 0 || t < 0)
            return false;
        
        TreeSet<Integer> set = new TreeSet<Integer>();
        
        for(int i = 0; i < nums.length; i++){
            int n = nums[i];
            if(set.floor(n) != null && ((long)n - (long)set.floor(n)) <= t ||
                set.ceiling(n) != null && ((long)set.ceiling(n) - (long)n) <= t){
                    return true;
                }
                
            set.add(n);
            
            if(i >= k){
                set.remove(nums[i - k]);
            }
        }
        
        return false;
    }
}


另外还有一种O(n)的bucket做法

https://leetcode.com/discuss/38206/ac-o-n-solution-in-java-using-buckets-with-explanation

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++) {
            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 (map.entrySet().size() >= k) {
                long lastBucket = ((long) nums[i - k] - Integer.MIN_VALUE) / ((long) t + 1);
                map.remove(lastBucket);
            }
            map.put(bucket, remappedNum);
        }
        return false;
    }
}


你可能感兴趣的:(LeetCode)