码迷,mamicode.com
首页 > 其他好文 > 详细

Contains Duplicate III

时间:2016-10-10 07:44:46      阅读:197      评论:0      收藏: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] andnums[j] is at most t and the difference between i and j is at most k.

 1 public class Solution {
 2     public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
 3         if(nums==null||nums.length<2||k<0||t<0)
 4             return false;
 5      
 6         TreeSet<Long> set = new TreeSet<Long>();
 7         for(int i=0; i<nums.length; i++){
 8             long curr = (long) nums[i];
 9      
10             long leftBoundary = (long) curr-t;
11             long rightBoundary = (long) curr+t+1; //right boundary is exclusive, so +1
12             SortedSet<Long> sub = set.subSet(leftBoundary, rightBoundary);
13             if(sub.size()>0)
14                 return true;
15      
16             set.add(curr);   
17      
18             if(i>=k){ // or if(set.size()>=k+1)
19                 set.remove((long)nums[i-k]);
20             }
21         }
22      
23         return false;
24     }
25 }

 

Contains Duplicate III

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5944452.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!