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.
题目要求:数组nums中,是否存在i, j,满足abs(nums[i]-nums[j]) <= t, abs(i-j) <= k。
使用了set对问题进行求解。
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if(t<0 || k<0 || nums.size()<2)
return false;
set<int> s;
for(int i = 0; i < nums.size(); i++){
if(i > k) s.erase(nums[i-k-1]);
set<int>::iterator it = s.lower_bound(nums[i]-t);
if(it != s.end() && abs(*it - nums[i]) <= t)
return true;
s.insert(nums[i]);
}
return false;
}
};
在完成了III之后,又把I和II做了。有了III的基础,I和II很容易就解决了。