problems:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
解题思路:
每访问一个数,把已经访问过的符合条件k的加入multiset中,同时要查看是否有符合条件t的 时间复杂度o(n)
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { multiset<int> set; for(int i=0;i<nums.size();i++) { if(set.size()==k+1) { set.erase(set.find(nums[i-k-1])); } auto it=set.lower_bound(nums[i]-t); //这儿不能用abs(nums[i]) 涉及到负数case 无法通过 [-1 -1] 2 0 if(it!=set.end()) { int gap = abs(nums[i]-*it); if(gap<=t) return true; } set.insert(nums[i]); } return false; } };