forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContainsDuplicate.II.cpp
28 lines (25 loc) · 873 Bytes
/
ContainsDuplicate.II.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Source : https://leetcode.com/problems/contains-duplicate-ii/
// Author : Hao Chen
// Date : 2015-06-12
/**********************************************************************************
*
* Given an array of integers and an integer k, find out whether there there are
* two distinct indices i and j in the array such that nums[i] = nums[j] and
* the difference between i and j is at most k.
*
*
**********************************************************************************/
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
unordered_map<int, int> m;
for (int i=0; i<nums.size(); i++) {
int n = nums[i];
if (m.find(n) != m.end() && i - m[n] <= k) {
return true;
}
m[n] = i;
}
return false;
}
};