Input: nums =[3,1,4,1,5], k =2Output: 2Explanation: 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.
To count unique k-diff pairs, we can use a hash map to count occurrences. For k > 0, for each unique number, check if num + k exists. For k = 0, count numbers that appear more than once.
classSolution {
publicintfindPairs(int[] nums, int k) {
if (k < 0) return 0;
Map<Integer, Integer> cnt =new HashMap<>();
for (int n : nums) cnt.put(n, cnt.getOrDefault(n, 0) + 1);
int ans = 0;
if (k == 0) {
for (int c : cnt.values()) if (c > 1) ans++;
} else {
for (int n : cnt.keySet()) if (cnt.containsKey(n + k)) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funfindPairs(nums: IntArray, k: Int): Int {
if (k < 0) return0val cnt = mutableMapOf<Int, Int>()
for (n in nums) cnt[n] = cnt.getOrDefault(n, 0) + 1var ans = 0if (k ==0) {
for (c in cnt.values) if (c > 1) ans++ } else {
for (n in cnt.keys) if (cnt.containsKey(n + k)) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deffindPairs(self, nums: list[int], k: int) -> int:
if k <0:
return0from collections import Counter
cnt = Counter(nums)
ans =0if k ==0:
for v in cnt.values():
if v >1:
ans +=1else:
for n in cnt:
if n + k in cnt:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use std::collections::HashMap;
impl Solution {
pubfnfind_pairs(nums: Vec<i32>, k: i32) -> i32 {
if k <0 { return0; }
letmut cnt = HashMap::new();
for n in nums { *cnt.entry(n).or_insert(0) +=1; }
letmut ans =0;
if k ==0 {
for&c in cnt.values() { if c >1 { ans +=1; } }
} else {
for&n in cnt.keys() { if cnt.contains_key(&(n + k)) { ans +=1; } }
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
findPairs(nums: number[], k: number):number {
if (k<0) return0;
constcnt=newMap<number, number>();
for (constnofnums) cnt.set(n, (cnt.get(n) ??0) +1);
letans=0;
if (k===0) {
for (constcofcnt.values()) if (c>1) ans++;
} else {
for (constnofcnt.keys()) if (cnt.has(n+k)) ans++;
}
returnans;
}
}