This is an “near by” problem that can be solved by Sliding Window. The k in the problem is somehow means contiguous.
And using a HashTable
to indicate that two values in the different position are equal.
The steps is following:
- Find two values at each side of window are equal.
- Return
true
if the offset between their indices is less than or equal k. Otherwise setleft
to the new position and continue.
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int left = 0;
unordered_map<int, int> indices;
for (auto right = 0; right < nums.size(); right++) {
auto iter = indices.find(nums[right]);
if (iter != indices.end()) {
if (abs(right - iter->second) <= k) {
return true;
}
left = iter->second + 1;
}
indices[nums[right]] = right;
}
return false;
}
};