diff --git a/cpp/2210/221021.cpp b/cpp/2210/221021.cpp new file mode 100644 index 0000000..bfcb0ee --- /dev/null +++ b/cpp/2210/221021.cpp @@ -0,0 +1,25 @@ +#include +#include + +/** + * 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& nums, int k) { + int n = nums.size(); + std::unordered_set 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; + } +}; diff --git a/cpp/2210/CMakeLists.txt b/cpp/2210/CMakeLists.txt index 9231094..b64967f 100644 --- a/cpp/2210/CMakeLists.txt +++ b/cpp/2210/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2210) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2210 221021-CN.cpp) +ADD_EXECUTABLE(2210 221021.cpp)