bool containsNearbyDuplicate(vector<int>& nums, int k)
{
unordered_map<int,int> re;
for (int i = 0; i < nums.size(); i++)
{
if (re.find(nums[i]) != re.end() && i  re[nums[i]] <= k)return true;
else re[nums[i]] = i;
}
return false;
}
Straightforward solution, using C++ STL

Here is my modified solution which guarantees only one duplicate:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> m; int d = 0; for (int i = 0; i < nums.size(); ++i) { if (m.find(nums[i]) != m.end()) { if (d > 0) return false; d = i  m[nums[i]]; } m[nums[i]] = i; } return d == 0 ? false : d <= k; } };