【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] and nums[j] is at most t and the difference between i and j is at most k.數據結構

提示:

看到題目以後,立刻想到了題目應該是要利用一個長度爲k的劃窗,那麼問題就在於用什麼數據結構來構造這個劃窗。因爲當新的數字進來後,咱們須要比較它和劃窗內其餘數字的大小關係,從搜索的效率角度出發,能夠使用BST,所以咱們選擇STL中的SET容器來構造這個劃窗。函數

思路也很簡單,當新進來一個數後,先在容器中尋找是否有比nums[i]-t大的數字,這一步能夠利用lower_bound函數實現,以後再比較比nums[i]-t大的數字中最小的那個與nums[i]的差,若是符合條件就返回true。post

另外不要忘記劃窗移動時,刪除和插入相應的元素。spa

代碼:

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        if (k < 0) {
            return false;
        }
        set<int> window;
        for (int i = 0; i < nums.size(); ++i) {
            if (i > k) {
                window.erase(nums[i-k-1]);
            }
            auto pos = window.lower_bound(nums[i] - t);
            if (pos != window.end() && *pos - nums[i] <= t) {
                return true;
            }
            window.insert(nums[i]);
        }
        return false;
    }
};
相關文章
相關標籤/搜索