[LeetCode] K-diff Pairs in an Array

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.

  • new solution update 2022.02.09
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
unordered_set<int> s, dup;
int res = 0;
for(int i = 0; i < nums.size(); i++) {
if(s.count(nums[i])) {
if(!k and !dup.count(nums[i])) {
res++;
dup.insert(nums[i]);
}
} else {
res += s.count(nums[i] - k);
res += s.count(nums[i] + k);
s.insert(nums[i]);
}
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
int res = 0;

unordered_map<int, int> m;
for(auto& num : nums) {
m[num]++;
}

if(k == 0) {
for(auto& num : m) {
if(num.second >= 2)
res++;
}
} else {
for(auto& num : m) {
if(m.count(num.first + k))
res++;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/10/PS/LeetCode/k-diff-pairs-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.