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 absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
思路:
我们使用multimap来存储num和其对应的下标,当第二次遇到时就可以直接计算两者之间的距离。
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
multimap<int, int> num_pos;
for (int i = 0; i<int(nums.size()); i++) {
if (num_pos.find(nums[i]) == num_pos.end()) {
num_pos.insert(make_pair(nums[i], i));
}
else {
auto range = num_pos.equal_range(nums[i]);
for (auto it = range.first; it != range.second; it++) {
if (i - (*it).second <= k)
return true;
}
num_pos.insert(make_pair(nums[i], i));
}
}
return false;
}
};