Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of unique pairs.
分析:
返回给定数组中不同k-diff对的个数。k-diff为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k。新建一个哈希表,建立数字与其出现次数之间的映射,遍历哈希表,若k为0,则哈希表中个数大于1的数字的个数即为不同k-diff对的个数;若k不为0,若哈希表中存在当前数字+k也存在,则res++。
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int res = 0, n = nums.size();
unordered_map<int, int> m;
for (int num : nums)
++m[num];
for (auto a : m) {
if (k == 0 && a.second > 1)
++res;
if (k > 0 && m.count(a.first + k))
++res;
}
return res;
}
};