class Solution {
public:
long long size;
bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
//桶排序
unordered_map<long,long> m;
size=valueDiff+1;
for(int i=0;i<nums.size();i++){
//控制数值
long long idx=getID(nums[i]);
if(m.find(idx)!=m.end()){
return true;
}
if(m.find(idx-1)!=m.end() && abs(nums[i] - m[idx-1]) <= valueDiff){
return true;
}
if(m.find(idx+1)!=m.end() && abs(nums[i] - m[idx+1]) <= valueDiff){
return true;
}
m[idx]=nums[i];
if(i>=indexDiff)
m.erase(getID(nums[i-indexDiff]));
}
return false;
}
long long getID(int x){
long long u=x*1L;
return u>=0?(u/size):(((u+1)/size)-1);
}
};
不是控制index,index只用滑动窗口 for循环+一个“ i>indexdiiff” 判断
抓valuediff 桶排序,一个桶里,一个valuediff gap.抓的是值。在一个桶里说明值是符合(3)条件