532. K-diff Pairs in an Array
class Solution {
public:
int findPairs(vector<int>& nums, int k) {
unordered_map<int, int> exist;
int res = 0;
if (k < 0) return 0; //因为是absolute diff(觉得纯粹深井冰
for (int num : nums) {
if (exist.count(num)) {
exist[num]++;
if (!k && exist[num] == 2) res++;
continue;
}
//考虑重复的数字,考虑数字重复时k=0怎么办,啊 然而[1,1,1,1,1],0 如果用一个set没辙
if (exist.count(num + k)) res++;
if (k && exist.count(num - k)) res++;
exist[num]++;
}
return res;
}
};
更干净的方法:直接count然后一次过计算
public class Solution {
public int findPairs(int[] nums, int k) {
if (nums == null || nums.length == 0 || k < 0) return 0;
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
for (int i : nums) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (k == 0) {
//count how many elements in the array that appear more than twice.
if (entry.getValue() >= 2) {
count++;
}
} else {
if (map.containsKey(entry.getKey() + k)) {
count++;
}
}
}
return count;
}
}