From 7d9b13b6b58277b68727fb5582eec24a258282f1 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Thu, 16 Jun 2022 13:46:44 +0800 Subject: [PATCH] add: 220616-CN --- cpp/2206/220616-CN.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ cpp/2206/CMakeLists.txt | 2 +- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 cpp/2206/220616-CN.cpp diff --git a/cpp/2206/220616-CN.cpp b/cpp/2206/220616-CN.cpp new file mode 100644 index 0000000..322b53e --- /dev/null +++ b/cpp/2206/220616-CN.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +/** + * 532. K-diff Pairs in an Array + * Given an array of integers nums and an integer k, return the number of unique k-diff pairs in the array. + * A k-diff pair is an integer pair (nums[i], nums[j]), where the following are true: + * - 0 <= i, j < nums.length + * - i != j + * - nums[i] - nums[j] == k + * Notice that |val| denotes the absolute value of val. + * + * Refer: 220209.cpp + */ + +class Solution { +public: + static int findPairs(const std::vector& nums, int k) { + int ans = 0; + if (k) { + std::unordered_set s; + for (int i : nums) { + if (s.count(i)) + continue; + if (s.count(i + k)) + ++ans; + if (s.count(i - k)) + ++ans; + s.insert(i); + } + } else { + std::unordered_map m; + for (int i : nums) + if (m[i]++ == 1) + ++ans; + } + return ans; + } +}; diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 3c4ac2a..1dc2d09 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220615-CN.cpp) +ADD_EXECUTABLE(2206 220616-CN.cpp)