adding exercise on map find function
This commit is contained in:
@@ -165,5 +165,6 @@ on whether or not the key was in a pair in the map.
|
|||||||
## 15.10 Leetcode Exercises
|
## 15.10 Leetcode Exercises
|
||||||
|
|
||||||
- [Leetcode problem 1: Two Sum](https://leetcode.com/problems/two-sum/). Solution: [p1_twosum.cpp](../../leetcode/p1_twosum.cpp).
|
- [Leetcode problem 1: Two Sum](https://leetcode.com/problems/two-sum/). Solution: [p1_twosum.cpp](../../leetcode/p1_twosum.cpp).
|
||||||
|
- [Leetcode problem 219: Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/description/). Solution: [p219_contains_duplicate_ii.cpp](../../leetcode/p219_contains_duplicate.cpp).
|
||||||
- [Leetcode problem 290: Word Pattern](https://leetcode.com/problems/word-pattern/). Solution: [p290_word_pattern.cpp](../../leetcode/p290_word_pattern.cpp).
|
- [Leetcode problem 290: Word Pattern](https://leetcode.com/problems/word-pattern/). Solution: [p290_word_pattern.cpp](../../leetcode/p290_word_pattern.cpp).
|
||||||
|
|
||||||
|
|||||||
18
leetcode/p219_contains_duplicate_ii.cpp
Normal file
18
leetcode/p219_contains_duplicate_ii.cpp
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool containsNearbyDuplicate(vector<int>& nums, int k) {
|
||||||
|
int size = nums.size();
|
||||||
|
// create the map, map key is the value of the vector element, map value is the index of that element in the vector.
|
||||||
|
map<int,int> map1;
|
||||||
|
for(int i=0;i<size;i++){
|
||||||
|
// if already exists
|
||||||
|
if(map1.find(nums[i])!=map1.end()){
|
||||||
|
if(i-map1[nums[i]]<=k){
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
map1[nums[i]]=i;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user