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;
}
};