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.
class Solution {
public:
bool containDup(vector<int>& nums){
int i = 0, z = nums.size();
for(;i<z-1;i++){
if(nums[i] == nums[i+1]){
return true;
}
}
return false;
}
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int z = nums.size();
int i, j;
vector<int> temp;
for(i=0;i<z;i++){
if(i+k < z-1){
temp.clear();
temp.insert(temp.begin(), nums.begin() + i, nums.begin() + i + k + 1);
sort(temp.begin(), temp.end());
if(containDup(temp)){
return true;
}
}else{
temp.clear();
temp.insert(temp.begin(), nums.begin() + i, nums.end());
sort(temp.begin(), temp.end());
if(containDup(temp)){
return true;
}else{
return false;
}
}
}
return false;
}
};
本文探讨了一个算法问题:在一个整数数组中,找出是否存在两个不同的索引i和j,使得nums[i] = nums[j]且i与j之间的差值不大于k。通过实现两个函数,我们首先检查数组中是否存在连续重复元素,然后检查是否存在距离不超过k的重复元素。
225

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



