leetcode--Contains Duplicate III

64 篇文章 0 订阅
43 篇文章 0 订阅

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.


题意:给定一个整形数组,检查是否存在两个序号i,j,要求nums[i]和nums[j]的差最多是t,同时i和j的差最多是k

分类:树


解法1:容易想到的思路是维护一个长度为k的窗口,每次检查新值和原窗口中值的差会不会超过t即可。

如果使用两重循环,时间复杂度是O(nk)会超时。我们使用TreeSet去检查差值,使复杂度为O(nLogk)。

SortedSet<E> subSet(E fromElement,E toElement)

set的subSet()方法可以指定一个范围,原来set中在这个范围内的数据,组成一个新的SortedSet返回。


import java.util.SortedSet;
public class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
        //input check  
        if(k<1 || t<0 || nums==null || nums.length<2) return false;  
          
        SortedSet<Long> set = new TreeSet<Long>();  
        for(int j=0; j<nums.length; j++) {  
        	SortedSet<Long> subSet =  set.subSet((long)nums[j]-t, (long)nums[j]+t+1); //对于新加入的元素,将与它差为t之外的数删除,返回剩下的数组成的SET
            if(!subSet.isEmpty()) return true;//如果还有数存在,说明符合条件  
              
            if(j>=k) {//如果窗口已经满了,删除SET中的第一个元素  
                set.remove((long)nums[j-k]);  
            }  
            set.add((long)nums[j]);//将新元素加入  
        }  
        return false;  
    }
}

同样的思路,我们可以这样写:

public class Solution {
    public boolean containsNearbyAlmostDuplicate(final int[] nums, int kk, long t) {
        if (nums.length < 2) return false;
        if (kk == 0) return false;
        TreeSet<Long> window = new TreeSet<Long>();

        for(int i=0;i<nums.length;i++) {
            // check dup, window size <= kk right now
            if ( window.floor(nums[i] + t) !=null && window.floor(nums[i]+t) >= nums[i]-t ) return true;
            window.add(new Long(nums[i]));
            if (i >= kk) {
                //remove one, the size has to be kk on the next fresh step
                window.remove(new Long(nums[i-kk]));
            }
        }
        return false;
    }
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值