Solution:
Keep tracking the past k elements by forming a BST for these k numbers. When new element coming, search BST to see if a target number exist. Remove the furthest element out of BST and insert current element to BST.
Here, we need to use some nice features provided by STL. In STL, a BST is implemented as a "set". In set, there exist a functionality that can search the smallest number that is greater than search key. by using this feature, we can determine if there exist a number that is in the range of [key-t, key+t].:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { | |
set<int> mySet; | |
for(int i=0; i<nums.size(); i++){ | |
// remove element outside k distance range from mySet | |
if(i-k-1>=0) | |
mySet.erase(nums[i-k-1]); | |
set<int>::iterator itup = mySet.upper_bound(nums[i]-t-1); | |
if(itup==mySet.end()){ | |
mySet.insert(nums[i]); | |
continue; | |
} | |
if(abs(*itup-nums[i])<=t ) | |
return true; | |
mySet.insert(nums[i]); | |
} | |
return false; | |
} | |
}; |
No comments:
Post a Comment