问题描述
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
思路分析
给一个数组,判断数组中是否存在nums[i]和nums[j],使得两者之间的index差最多为k时,两个元素的差做多为t。
使用set来保存一个长度为k的记录,来判断其中的元素有没有符合条件的。c++的set是用红黑树实现的,set本身就是有序的。循环nums中的元素,如果循环到的元素超过了k,就将最前面的元素也就是nums[i - k - 1]erase。然后使用set的lower_bound方法,返回set中大于等于nums[i] - t的元素,如果有就返回true。每次循环结束向set中插入新的值。
因为可能有越界的情况产生,使用long long的set防止越界。
代码
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (k <= 0 || t < 0 || nums.size() < 2)
return false;
set<long long> window;
for (int i = 0; i < nums.size(); ++i) {
if (i > k && i - k - 1 < nums.size())
window.erase(nums[i - k - 1]);
auto it = window.lower_bound((long long)nums[i] - t);
if (it != window.cend() && *it - nums[i] <= t)
return true;
window.insert(nums[i]);
}
return false;
}
};
时间复杂度:
O(nlogk)
空间复杂度:
O(k)
反思
lower_bound和upper_bound的使用:upper_bound返回的是大于指定值的iterator。