Contains Duplicate III
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.
There are two elements in the array, their value is less than or equal to T, and the subscript is less than or equal to K.
JavaScript time is very loose, violence O (n^2) directly can be past, but this question should be hope we use binary search tree.
K can be seen as a sliding window, for a new number, can be imagined to be placed on the left or right of the window, if the number +t or-t after falling in the window, directly return true.
Https://leetcode.com/discuss/38177/java-o-n-lg-k-solution
Java BST:
1 Public classSolution {2 Public BooleanContainsnearbyalmostduplicate (int[] Nums,intKintt) {3Treeset<integer> TreeSet =NewTreeset<integer>();4 for(inti = 0; i < nums.length; i++){5Integer floor = Treeset.floor (Nums[i] +t);6Integer ceiling = treeset.ceiling (Nums[i]-t);7 if(Floor! =NULL&& Floor >=Nums[i])8|| (Ceiling! =NULL&& ceiling <= nums[i]))return true;9 Treeset.add (Nums[i]);Ten if(Treeset.size () > K) treeset.remove (Nums[i-K]); One } A return false; - } -}
Brute Force:
1 /**2 * @param {number[]} nums3 * @param {number} K4 * @param {number} t5 * @return {Boolean}6 */7 varContainsnearbyalmostduplicate =function(Nums, K, t) {8 for(vari = 0; i < nums.length; i++)9 for(varj = i + 1; J < Nums.length; J + +)Ten if(Math.Abs (Nums[i]-nums[j]) <= t && math.abs (I-J) <=k) One return true; A return false; -};
[Leetcode] [Java] Contains Duplicate III