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.
解题思路:
给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k。
其中式b是式c的充分非必要条件,因为逆否命题与原命题等价,所以:
有两个地方需要注意:
1、该题目可能会int类型溢出,因此需要先转化成long long类型。
2、map和unordered_map并不是按插入顺序排序的。因此还需要用一个队列来维持一个滑动窗口。
下面是C++代码:
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(k<1||t<0){
return false;
}
unordered_map<int, long long> nums_map;
queue<int> keys; //顺序存储的一些键值
int len = nums.size();
for(int i=0; i<len; i++){
int key = nums[i]/max(t, 1);
for(int j=key-1; j<=key+1; j++){
if(nums_map.find(j)!=nums_map.end() && abs(nums_map[j] - nums[i])<=(long long)t){
return true;
}
}
nums_map[key]=nums[i];
keys.push(key);
if(nums_map.size()>k){
nums_map.erase(keys.front());
keys.pop();
}
}
return false;
}
};
参考链接:http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/