Skip to content

Commit 4977ddd

Browse files
authored
Create solution.cpp
1 parent ea08efa commit 4977ddd

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

ContainsDuplicateII/solution.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <unordered_map>
2+
3+
class Solution {
4+
public:
5+
bool containsNearbyDuplicate(vector<int>& nums, int k)
6+
{
7+
// Store indices with the keys are their values
8+
unordered_map<int, int> hashmap;
9+
10+
for (int i=0; i<nums.size(); i++)
11+
{
12+
// Check if the current value was added before
13+
if (hashmap.count(nums.at(i)))
14+
{
15+
// The current value is a duplicate
16+
// Check if the current index and past index are within k appart
17+
if (i - hashmap[nums.at(i)] <= k)
18+
{
19+
return true;
20+
}
21+
}
22+
23+
// Add new index and value to hashmap
24+
hashmap[nums.at(i)] = i;
25+
}
26+
27+
// No duplicates were within k if we reached here
28+
return false;
29+
}
30+
};

0 commit comments

Comments
 (0)