[LeetCode] Contains Duplicate II

219. Contains Duplicate II

Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> mp;
for(int i = 0; i < nums.size(); i++) {
if(mp.count(nums[i]) and i - mp[nums[i]] <= k) return true;
mp[nums[i]] = i;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/21/PS/LeetCode/contains-duplicate-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.