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。
如果: | nums[i] - nums[j] | <= t 式a等價: | nums[i] / t - nums[j] / t | <= 1 式b推出: | floor(nums[i] / t) - floor(nums[j] / t) | <= 1 式c?等價: floor(nums[j] / t) ∈ {floor(nums[i] / t) - 1, floor(nums[i] / t), floor(nums[i] / t) + 1} 式d
其中式b是式c的充分非必要條件,因為逆否命題與原命題等價,所以:
如果: floor(nums[j] / t) ? {floor(nums[i] / t) - 1, floor(nums[i] / t), floor(nums[i] / t) + 1} 非d推出: | nums[i] - nums[j] | > t 非a
用一個hash表來儲存滑動視窗的數值,其中索引值為nums[i]/t,對於數值nums[k],若存在鍵為nums[k]/t,nums[k]/t-1,nums[k]/t+1,再比較他們的數值。
有兩個地方需要注意:
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/