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; } };
相似題目:
參考資料:
https://leetcode.com/discuss/38195/short-c-solution
http://www.cnblogs.com/easonliu/p/4544073.html