add: 220616-CN

This commit is contained in:
Eat-Swap 2022-06-16 13:46:44 +08:00
parent 68da6c82b3
commit 7d9b13b6b5
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 41 additions and 1 deletions

40
cpp/2206/220616-CN.cpp Normal file
View File

@ -0,0 +1,40 @@
#include <vector>
#include <unordered_set>
#include <unordered_map>
/**
* 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<int>& nums, int k) {
int ans = 0;
if (k) {
std::unordered_set<int> 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<int, int> m;
for (int i : nums)
if (m[i]++ == 1)
++ans;
}
return ans;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2206)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2206 220615-CN.cpp) ADD_EXECUTABLE(2206 220616-CN.cpp)