Given an array of integers, find out whether there is II distinct indices i and J in the array such th At the difference between nums[i] and Nums[j] are at most T and the difference between I and J I S at the most K.
ref:http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/
That's a good thing. "Sliding window" procedure here
, newly learned a structure treeset
The following references the explanation of images "
Solution II: "Sliding window" + TreeSet
Reference Leetcode Discuss:https://leetcode.com/discuss/38177/java-o-n-lg-k-solution
The TreeSet data structure (JAVA) is implemented using red-black trees and is a balanced binary tree.
The data structure supports the following operations:
1. Floor () method returns the largest element in the set that ≤ the given element, or null if no such element exists.
2. The ceiling () method returns the smallest element in the set ≥ the given element, or null if no such element exists.
”
There's an easy eight-brother place.
N<=t+set.floor (n))
Can not be written n-t "= ...
Public classSolution { Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {if(k<1| | T<0)return false; TreeSet<Integer> set =NewTreeset<integer>(); for(inti=0;i<nums.length;i++){ intn =Nums[i]; if((Set.floor (n)! =NULL&& N<=t+set.floor (n)) | | (Set.ceiling (n)! =NULL&& set.ceiling (n) <=t+N))return true; Set.add (n); if(i>=k) Set.remove (Nums[i-K]); } return false; }}
Contains Duplicate III