LeetCode 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 difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

思路分析:这题有几个要注意的地方:第一是如何快速搜索是否存在于某个数差值在t以内的数,可以使用TreeSet的subSet函数,可以返回在TreeSet中从在[lower,upper)的数,注意是前闭后开,这个函数返回的是SortedSet接口类型,TreeSet基于BST实现,特别适合于某个range里面的数的快速查找,下面的算法复杂度是O(nlogk)。第二,和Contains Duplicate的前面两题一样,有“the difference between i and j is at most k.”这样的限定的题目我们可以考虑维护一个长度为k的滑动窗口。第三,如果用Integer类型,这题有个test case会使得nums[i] + t + 1溢出变成负数,因此需要使用Long类型来保存数,要注意类型转换。

AC Code

import java.util.SortedSet;  // the return value of subset is SortedSet(Interface) type
public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        //1018
        if(nums == null || nums.length < 2 || k < 1 || t < 0) return false; // t is at least 0, k is at least 1
        SortedSet<Long> windowNumSet = new TreeSet<Long>();
        for(int i = 0; i < nums.length; i++){
            SortedSet<Long> set = windowNumSet.subSet((long)nums[i]-t, (long)nums[i] + t + 1);
            if(!set.isEmpty()) return true;
            if(i >= k) windowNumSet.remove((long)nums[i-k]);
            windowNumSet.add((long)nums[i]);
        }
        return false;
        //1026
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值