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 are at the most K.
Tips:
See the topic, immediately think of the topic should be to use a length of the window of k, then the problem is to use what data structure to construct the window. Since when the new number comes in, we need to compare it to the size of other numbers in the window, we can use BST from the point of view of the efficiency of the search, so we choose the Set container in STL to construct the window.
The idea is also very simple, when the new come in a number, first in the container to find whether there is larger than the number of nums[i]-t, this step can be achieved by using the Lower_bound function, and then compare the nums[i]-t larger than the number of the smallest and nums[i] difference, Returns true if the condition is met.
Also do not forget to delete and insert the corresponding element when the window is moved.
Code:
classSolution { Public: BOOLContainsnearbyalmostduplicate (vector<int>& Nums,intKintt) {if(K <0) { return false; } Set<int>window; for(inti =0; I < nums.size (); ++i) {if(I >k) {window.erase (nums[i-k-1]); } Auto Pos= Window.lower_bound (Nums[i]-t); if(pos! = window.end () && *pos-nums[i] <=t) {return true; } window.insert (Nums[i]); } return false; }};
"Leetcode" 220. Contains Duplicate III