2022-10-21 Daily Challenge
Today I have done leetcode's October LeetCoding Challenge with cpp.
October LeetCoding Challenge 21
Description
Contains Duplicate II
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
int len = nums.size();
unordered_set<int> st;
for(int i = 0; i < k && i < len; ++i) {
if(st.count(nums[i])) return true;
st.insert(nums[i]);
}
for(int i = k; i < len; ++i) {
if(st.count(nums[i])) return true;
st.insert(nums[i]);
st.erase(nums[i - k]);
}
return false;
}
};
// Accepted
// 52/52 cases passed (219 ms)
// Your runtime beats 84.4 % of cpp submissions
// Your memory usage beats 91.47 % of cpp submissions (72.2 MB)