The key is to keep updating hash table when duplicate is met.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool containsNearbyDuplicate(vector<int>& nums, int k) { | |
unordered_map<int, int> myMap; | |
for(int i=0; i<nums.size(); i++){ | |
if(myMap[nums[i]]!=0){ | |
if(abs(i+1-myMap[nums[i]])<=k) | |
return true; | |
myMap[nums[i]]=i+1; | |
} | |
else | |
myMap[nums[i]]=i+1; | |
} | |
return false; | |
} | |
}; |
Round 2 solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool containsNearbyDuplicate(vector<int>& nums, int k) { | |
if(nums.size()<1) | |
return false; | |
unordered_map<int, int> myHash; | |
for(int i=0; i<nums.size(); i++){ | |
auto it = myHash.find(nums[i]); | |
if(it==myHash.end()) | |
myHash[nums[i]]=i; | |
else{ | |
if(i-it->second<=k) | |
return true; | |
myHash[nums[i]]=i; | |
} | |
} | |
return false; | |
} | |
}; |
No comments:
Post a Comment