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 jis at most k.
Subscribe to see which companies asked this question
bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, int> hash; int i = 0; for (auto num : nums) { unordered_map<int, int>::iterator iter = hash.find(num); if (iter == hash.end()) hash.insert(make_pair(num, i)); else { if (i - (*iter).second <= k) return true; (*iter).second = i; } ++i; } return false; }