Created
January 6, 2018 05:57
-
-
Save s4553711/f808b9b30c32fd036602f3d0ed18d544 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { | |
private: | |
bool countWithSet(vector<int>& nums, int k) { | |
unordered_set<int> s; | |
for(int i = 0; i < nums.size(); i++) { | |
if (i > k) s.erase(nums[i - k - 1]); | |
if (s.find(nums[i]) != s.end()) return true; | |
s.insert(nums[i]); | |
} | |
return false; | |
} | |
bool countWithMap(vector<int>& nums, int k) { | |
unordered_map<int, int> nmap; | |
for(int i = 0; i < nums.size(); i++) { | |
if (nmap.count(nums[i]) == 0) { | |
nmap[nums[i]] = i; | |
} else if (i - nmap[nums[i]] <= k) { | |
return true; | |
} else { | |
nmap[nums[i]] = i; | |
} | |
} | |
return false; | |
} | |
public: | |
bool containsNearbyDuplicate(vector<int>& nums, int k) { | |
if (nums.size() == 0 || nums.size() == 1 || k <= 0) return false; | |
if (k >= nums.size()) k = nums.size() - 1; | |
return countWithMap(nums, k); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment