#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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值