给定一个整数数组,判断数组中是否有两个不同的索引 i 和 j,使得 nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ。
示例 1:
输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:
输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(nums.size() <= 1 || k <= 0 || t < 0) return false;
map<int, int> mapRepo;
for(int i = 0 ; i <= k && i < nums.size(); i++) //先比较前k个元素
{
if(mapRepo.find(nums[i]) != mapRepo.end()) //相同的元素肯定符合条件
return true;
if(t > 0)
{
for(auto it = mapRepo.begin(); it != mapRepo.end(); it++) //遍历map中的元素,差值小于t的符合要求
{
if(fabs((long)(it->first) - (long)(nums[i])) <= t)
return true;
}
}
mapRepo[nums[i]] = i;
}
for(int i = k+1; i < nums.size(); i++) //对于大于k的情况,每次先剔除掉map的第一个元素,剩余的匹配方式相同
{
mapRepo.erase(nums[i-k-1]);
if(mapRepo.find(nums[i]) != mapRepo.end())
return true;
if(t > 0)
{
for(auto it = mapRepo.begin(); it != mapRepo.end(); it++)
{
if(fabs((long)(it->first) - (long)(nums[i])) <= t)
return true;
}
}
mapRepo[nums[i]] = i;
}
return false;
}
};