1. 程式人生 > >[LeetCode] Contains Duplicate III 包含重複值之三

[LeetCode] 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.

這道題跟之前兩道Contains Duplicate 包含重複值Contains Duplicate II 包含重複值之二的關聯並不是很大,前兩道起碼跟重複值有關,這道題的焦點不是在重複值上面,反而是關注與不同的值之間的關係,這裡有兩個限制條件,兩個數字的座標差不能大於k,值差不能大於t。這道題如果用brute force會超時,所以我們只能另闢蹊徑。這裡我們使用map資料結構來解,用來記錄數字和其下標之間的對映。 這裡需要兩個指標i和j,剛開始i和j都指向0,然後i開始向右走遍歷陣列,如果i和j之差大於k,且m中有nums[j],則刪除並j加一。這樣保證了m中所有的數的下標之差都不大於k,然後我們用map資料結構的lower_bound()函式來找一個特定範圍,就是大於或等於nums[i] - t的地方,所有小於這個閾值的數和nums[i]的差的絕對值會大於t (可自行帶數檢驗)。然後檢測後面的所有的數字,如果數的差的絕對值小於等於t,則返回true。最後遍歷完整個陣列返回false。程式碼如下:

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

相似題目:

參考資料: