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.
Map:
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
map<int, int> mp;
map<int, int>::iterator it = mp.end();
for(int i= 0; i < nums.size(); i++){
it = mp.find(nums[i]);
if(it != mp.end()){
if(abs(it->second - i) <= k) return true;
else mp[nums[i]] = i;
}else{
mp[nums[i]] = i;
}
}
return false;
}
};

本文介绍了一种使用C++ map数据结构解决寻找数组中是否存在两个不同的索引i和j,使得nums[i]=nums[j]且i与j之间的绝对差不超过k的问题的方法。通过迭代数组并利用map来跟踪每个元素最后一次出现的位置,可以有效地判断是否存在这样的重复元素。
670

被折叠的 条评论
为什么被折叠?



