Description
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 absolute difference between i and j is at most k.
My solution
想法主要有两个:
1. 参照leetcode 217的方法, argsort一下, 对于相邻元素判断是否相同, 注意这里sort返回索引, 加一步判断索引差值即可. 这个思路用python较好实现.
2. 建立一个dict, key是nums的元素, value是其索引(用list方式存储), 判断一下同一个key多value的value之差.
上述两种思路都有点复杂, 同时, 因为题干只要求return bool, 自己的做法仍然是抠出来所有情况, 是有很大冗余的.
Discuss
采用滑窗方式, 窗口大小为题干中的k. 维护一个大小为k的set, 如果窗口范围内, 有新的重复元素来到, 是与set的无重复性冲突的.
bool containsNearbyDuplicate(vector<int>& nums, int k) {
set<int> cand;
for (int i = 0; i < nums.size(); i++) {
if (i > k) cand.erase(nums[i-k-1]);
if (!cand.insert(nums[i]).second) return true;
}
return false;
}
关于.second解释如下:
I searched online and found the answer.
The pair::first will store either the newly inserted element or the elements that has its same value in the set.
The pair::second will indicate the success or failure of inserting the new value.
We can use the followings:
if(!set.insert(item).second){
the content of insert failure to user;
}
Thanks