解析
同上一篇《力扣-数组-217 存在重复元素》存储在重复元素的思路,重点是放在结构体里,保存之前的下标即可。
代码
cpp
class Solution {
public:
struct myNode{
int index;
int value;
};
static bool cmp(myNode a, myNode b){
return a.value < b.value;
}
bool containsNearbyDuplicate(vector<int>& nums, int k) {
struct myNode nodes[nums.size()];
for(int i = 0; i< nums.size(); i++){
nodes[i].index = i;
nodes[i].value = nums[i];
}
sort(nodes, nodes+nums.size(), cmp);
int last = nodes[0].value;
int index = nodes[0].index;
bool res = false;
for(int i = 1; i < nums.size(); i++){
if(nodes[i].value == last && abs(index - nodes[i].index) <= k){
res = true;
break;
}
index = nodes[i].index;
last = nodes[i].value;
}
return res;
}
};