题目
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.
答案
class Solution {
public int findPairs(int[] nums, int k) {
if(k < 0) return 0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int num : nums)
map.put(num, (map.get(num) == null)? 1:map.get(num) + 1);
int ans = 0;
for(int num : map.keySet()) {
Integer n = map.get(num);
if(k == 0) {
if(n > 1) ans++;
}
else {
if(map.containsKey(num - k)) {
ans++;
}
/*
You may search for num - k or num + k, but not both, otherwise you get duplicated pairs
if(map.containsKey(num + k)) {
ans++;
}
*/
}
}
return ans;
}
}