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.


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

分类:树


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

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

[java]  view plain  copy
  1. SortedSet<E> subSet(E fromElement,E toElement)  

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


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

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

[java]  view plain  copy
  1. public class Solution {  
  2.     public boolean containsNearbyAlmostDuplicate(final int[] nums, int kk, long t) {  
  3.         if (nums.length < 2return false;  
  4.         if (kk == 0return false;  
  5.         TreeSet<Long> window = new TreeSet<Long>();  
  6.   
  7.         for(int i=0;i<nums.length;i++) {  
  8.             // check dup, window size <= kk right now  
  9.             if ( window.floor(nums[i] + t) !=null && window.floor(nums[i]+t) >= nums[i]-t ) return true;  
  10.             window.add(new Long(nums[i]));  
  11.             if (i >= kk) {  
  12.                 //remove one, the size has to be kk on the next fresh step  
  13.                 window.remove(new Long(nums[i-kk]));  
  14.             }  
  15.         }  
  16.         return false;  
  17.     }  
  18. }

原文链接http://blog.csdn.net/crazy__chen/article/details/47279997

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值