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.
思想:创建一个集合,在这个集合中维护k个元素,这k个元素是相对于当前遍历的元素的前k个元素,当遍历一个新的元素时,检查前k个元素中是否有相同的元素出现。
#include<iostream>
#include<unordered_set>
#include<vector>
using namespace std;
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_set<int> preKValueSet;
if(k <= 0)
return false;
if(k >= nums.size())
k = nums.size() - 1;
for(int i = 0; i < nums.size(); i++)
{
if(i > k)
preKValueSet.erase(nums[i - k - 1]);
if(preKValueSet.find(nums[i]) != preKValueSet.end())
return true;
preKValueSet.insert(nums[i]);
}
return false;
}
};
还有一种使用哈希表的方式如下
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> m;
for (int i = 0; i < nums.size(); ++i) {
if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) return true;
else m[nums[i]] = i;
}
return false;
}
};