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 most K.
Different from the previous question, this way not only has the index distance limit, but also adds two values and the request. This requires the selected data structure to support fast search by value. TreeSet is chosen because it is internally implemented with a red-black tree, all nodes are sorted from low to high by natural order, can provide add/remove/contain operation of O (Logn), and have floor and ceiling two method, Can be used to quickly find in a certain range. There is a test case on the leetcode that is the integer value overflow variable complex, so in the second solution below, a long value is used, and you should pay attention to the int to a long type of cast.
Another thing to note about TreeSet is that it is implemented based on the interface of comparable, and set is based on equals. So we need to consider the implementation of CompareTo to ensure the unification of the two. Also highlighted in the relevant documentation.
Solution One:
1 Public Static BooleanContainsNearbyAlmostDuplicate1 (int[] Nums,intKintt) {2 if(k<1 | | t<0)return false;3 4Treeset<integer> set =NewTreeset<integer>();5 for(inti=0;i<nums.length;i++){6 intCurrent =Nums[i];7 if(Set.floor (current)! =NULL&& current<= Set.floor (current) +t) | |8(Set.ceiling (current)! =NULL) && current>=set.ceiling (current)-t)9 return true;Ten Set.add (current); One A if(i>=k) -Set.remove (nums[i-K]); - } the return false; - } -
Solution Two:
1 Public Static BooleanContainsNearbyAlmostDuplicate2 (int[] Nums,intKintt) {2 if(k<1 | | t<0)return false;3 4Treeset<long> set =NewTreeset<long>();5 for(inti=0;i<nums.length;i++){6 intCurrent =Nums[i];7sortedset<long> subset = Set.subset ((Long) Current-t, (Long) current+t+1);8 9 if(!subset.isempty ())return true;TenSet.add ((Long) (current); One if(I >=k) set.remove ((Long) nums[i-k]);//remember to cast it to long A } - return false; -}
reference:http://www.programcreek.com/2014/06/leetcode-contains-duplicate-iii-java/
Leetcode–remove duplicates from Sorted List III (Java)