@luo_seu I had a question about the time complexity of your code. You are iterating over all the n-elements and using the std::find() method. Iterating over all the elements is an O(n) operation, while using std::find() each time is again O(n) in the worst case. So, is the total worst case complexity of your code O(n^2)?

Here is my code with the same idea, which is more simpler:

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Set<Integer> set = new HashSet<Integer>();
int i = 0, j = 0;
for (; j < nums.length; j++) {
if (j - i > k) {
set.remove(nums[i]);
i++;
}
if (set.contains(nums[j])) return true;
set.add(nums[j]);
}
return false;
}
}

map is typically implemented with trees (e.g. red-black tree), whereas unordered_map is a hashset. Element access for map is typically in O(log n) while hashset is in avg O(1).