C++ 6 line solution. simple code and easy understanding

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

• Sliding window, nice

• Hi! here is my short C++ solution using hashMap.

``````bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> hashMap;
for(int i = 0; i < nums.size(); ++i) {
if(hashMap.find(nums[i]) != hashMap.end() && i - hashMap[nums[i]] <= k)  return true;
hashMap[nums[i]] = i;
}
return false;
}``````

• Thank you for your solution, but could you tell me `cand.insert(nums[i]).second` , what is `.second` represents? Is `cand.insert(nums[i]).second` equal to number of `nums[i]` existed in `cand` ?

• Is `.second` means whether success to insert `nums[i]`?

• I have figured it out. Many thanks for your solution.

• Thanks. I am also performing sliding window but without maintaining set, my question here is what prompted you to go for this O(k) space solution when there is nothing mentioned. Did you try O(1) space solution before?

• Can you please explain what this .second means here?

• can anybody explain what's the meaning of the code
if(!set.insert(nums[i]).second)
what does the SECOND mean?
Thanks a lot

• @jcheng.atl
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

• @lchen77 very nice,I understand,thank you.

• if you do not use the STL often, review it and you will found it's so easy.

• @fastcode same code!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.