Given an array of integers and an integer k, return true if and only if 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.
hash map
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int,int> temp;
for(int i=0;i<nums.size();++i){
if(temp.find(nums[i])==temp.end()){
temp[nums[i]] = i;
}
else{
if(k>=(i-temp[nums[i]]))
return true;
}
}
return false;
}
};
本文介绍了一种使用哈希表解决LeetCode中寻找数组内k距离内的重复元素问题的方法。通过C++实现,利用unordered_map存储元素及其索引,快速判断是否存在符合条件的重复项。
1381

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



