https://leetcode.com/problems/contains-duplicate-ii/description/
Solution 1. Use map to store the index for each distinct number.
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.size()<2) return false;
unordered_map<int, int> mp;
for(int i=0; i<nums.size(); i++) {
if(mp.count(nums[i]))
if(i - mp[nums[i]]<=k) return true;
mp[nums[i]] = i;
}
return false;
}
Solution 2. Use unordered_set to maintain a set containing nums[i-k,...,i-1].
bool containsNearbyDuplicate(vector<int>& nums, int k) {
if(nums.size()<2 || k<=0) return false;
unordered_set<int> st;
for(int i=0; i<nums.size(); i++) {
if(st.count(nums[i]))
return true;
else {
if(i-k>=0) st.erase(nums[i-k]);
st.insert(nums[i]);
}
}
return false;
}
No comments:
Post a Comment