Skip to content

Commit 4e271b2

Browse files
committed
Create contains-duplicate-ii.cpp
1 parent 4a9ef6b commit 4e271b2

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

C++/contains-duplicate-ii.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
bool containsNearbyDuplicate(vector<int>& nums, int k) {
7+
unordered_map<int, int> hash;
8+
for (int i = 0; i < nums.size(); ++i) {
9+
if (hash.find(nums[i]) == hash.end()) {
10+
hash[nums[i]] = i;
11+
} else {
12+
// It the value occurs before, check the difference.
13+
if (i - hash[nums[i]] <= k) {
14+
return true;
15+
}
16+
// Update the index of the value.
17+
hash[nums[i]] = i;
18+
}
19+
}
20+
return false;
21+
}
22+
};

0 commit comments

Comments
 (0)