-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
35 lines (33 loc) · 1014 Bytes
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <cstddef>
#include <cstdlib>
#include <unordered_map>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
// No constance space constraint.
// -10^9 <= nums[i] <= 10^9 => Prolly use an unordered_map instead of an
// array.
// Since we are traversing left-to-right, i.e., the indices will be in
// sorted order, we just need to maintain the last-seen idx of each unique
// number.
std::unordered_map<int, int> prevIdx;
for (int i = 0; i < nums.size(); ++i) {
auto iter = prevIdx.find(nums[i]);
if (iter == prevIdx.end()) {
prevIdx[nums[i]] = i;
continue;
}
// Otherwise, there was a duplicate, check distance
if (std::abs(iter->second - i) <= k) {
return true;
}
// otherwise, update the last seen
iter->second = i;
}
// if we reach here, there is no matching pair of numbers
return false;
}
};