Title: Given An array of integers, find out whether there is II distinct indices i and J in the array such That the difference between nums[i] and Nums[j] are at most T and the difference between I and j are at the most K.
Train of thought: compared to I and II, slightly complex, conventional thinking, maintenance of a long k window, if the cycle to determine the time-out, taking into account the characteristics of the problem, using the relevant methods in TreeSet to achieve:
Ceiling (E): Returns the minimum value that is greater than or equal to the parameter E in set, and none returns null;
Floor (E): Returns the minimum value of the set that is less than or equal to the parameter E, or null if none;
In the range of K-size, every more than one, remove a value from the beginning.
Code:
Public classSolution { Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {TreeSet<Long> set =NewTreeset<long>(); for(inti = 0; i < nums.length; i++){ if(i-k-1>=0) Set.remove (Long) nums[i-k-1]); if(Set.ceiling (Long) nums[i])! =NULL){//the smallest element greater than or equal to Nums[i] Longtemp = set.ceiling ((Long) nums[i]); if(Math.Abs (temp-nums[i]) <=t)return true; } if(Set.floor (Long) nums[i])! =NULL){//the smallest element greater than or equal to Nums[i] Longtemp = Set.floor ((Long) nums[i]); if(Math.Abs (temp-nums[i]) <=t)return true; } Set.add ((Long) nums[i]); } return false; }}
Also on the Internet to see a more concise method, but also the use of TreeSet in the method:
Sortedset<e> subset (e fromelement, E toelement)
Returns a partial view of this set whose elements are from fromelement (including) to Toelement (not included).
It is possible to simply leetcode the two judgments together (though not on the cannot find Symbol:class SortedSet so you need to import the package yourself, notice the import above).
Code:
ImportJava.util.SortedSet; Public classSolution { Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {if(t<0) return false; TreeSet<Long> set =NewTreeset<long>(); for(inti = 0; i < nums.length; i++){ if(i-k-1>=0) Set.remove (Long) nums[i-k-1]); SortedSet<Long> subset = Set.subset ((Long) Nums[i]-t, (Long) nums[i]+t+1); //T for negative words Fromkey > Tokey so start to judge if(!subset.isempty ())return true; Set.add ((Long) nums[i]); } return false; }}
Reference: http://blog.csdn.net/thinking2013/article/details/46336373
http://blog.csdn.net/xudli/article/details/46323247
[Leetcode-java] Contains Duplicate III