add: 221021

This commit is contained in:
Eatswap 2022-10-21 19:41:09 +08:00
parent a221db8b47
commit aa9405e07f
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 26 additions and 1 deletions

25
cpp/2210/221021.cpp Normal file
View File

@ -0,0 +1,25 @@
#include <vector>
#include <unordered_set>
/**
* 219. 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.
*/
class Solution {
public:
static bool containsNearbyDuplicate(const std::vector<int>& nums, int k) {
int n = nums.size();
std::unordered_set<int> s(nums.begin(), nums.begin() + std::min(k, n));
if (s.size() != std::min(k, n))
return true;
for (int i = k; i < n; ++i) {
if (s.count(nums[i]))
return true;
s.insert(nums[i]);
s.erase(nums[i - k]);
}
return false;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2210)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2210 221021-CN.cpp)
ADD_EXECUTABLE(2210 221021.cpp)