LeetCode刷题实战220:存在重复元素 III
共 2786字,需浏览 6分钟
·
2021-03-25 14:07
Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k.
示例
示例 1:
输入: nums = [1,2,3,1], k = 3, t = 0
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1, t = 2
输出: true
示例 3:
输入: nums = [1,5,9,1,5,9], k = 2, t = 3
输出: false
解题
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
set<long> s;
for(int i = 0; i < nums.size(); i++) {
auto it = s.lower_bound(nums[i] - long(t));
if(it != s.end() && *it - nums[i] <= t) {
return true;
}
s.insert(nums[i]);
if(s.size() > k) {
s.erase(nums[i - k]);
}
}
return false;
}
};