leetcode 220. Contains Duplicate III

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] andnums[j] is at most t and the difference between i and j is at most k.


一開始以爲和前兩道差不多,做了之後發現不太一樣,如果用前兩道題的方法,一般都會超時,即使判斷t和k大小分別用不同的方式還是超時。

所以採用滑動窗口,保證map裏面的所有key下標只差在k以內,然後找一個和nums[i]差值在t以內的值。

lower_bound(x)和upper_bound的區別:

lower_bound(x)返回一個key>=x的iterator

upper_bound(x)返回一個key>x的iterator

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        map<int, int> mp;
        int j = 0;
        map<int, int>::iterator it = mp.end();
        for(int i = 0; i < nums.size(); i++){
            if(i - j > k) mp.erase(nums[j++]);
            it = mp.lower_bound(nums[i]-t);
            if(it != mp.end() && it->first - nums[i] <= t)return true;
            mp[nums[i]] = i;
        }
        return false;
    }
};







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章