[LeetCode] Contains Duplicate III

220. 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 absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
multiset<int> sets;
for(int i = 0; i < nums.size(); i++) {
auto it = sets.insert(nums[i]);
auto lower = it, upper = ++it;
if((lower != sets.begin() && *(--lower) >= (INT_MIN + t > nums[i] ? INT_MIN : nums[i] - t)) ||
(upper != sets.end() && *upper <= (INT_MAX - t < nums[i] ? INT_MAX : nums[i] + t)))
return true;
if(i >= k)
sets.erase(nums[i - k]);
}

return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/01/14/PS/LeetCode/contains-duplicate-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.