Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.
#include <vector>
#include <unordered_map>
#include <iostream>
using namespace std;
// Given an array of integers and integer k, find out whether there are two distinct
// indices i and j in the array such that nums[i] == nums[j] and the difference between i and j is at most k.
// use hashmap.
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.size() <= 1) return false;
unordered_map<int, int> dataToIndex;
for(int i = 0; i < nums.size(); ++i) {
auto iter = dataToIndex.find(nums[i]);
if(iter == dataToIndex.end()) {
dataToIndex.insert({nums[i], i});
} else {
if(i - iter->second <= k) {return true;}
else {iter->second = i;}
}
}
return false;
}
int main(void) {
vector<int> nums{-1, -1};
bool len = containsNearbyDuplicate(nums, 1);
cout << len << endl;
}