K-diff Pairs in an Array
Question
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.
Solution
可以用非常簡單的 Set 解決,但總覺得很難想(連看解答我也覺得一知半解)。還是覺得用 Map 比較直觀
public int findPairs(int[] nums, int k) {
if (k < 0) { return 0; }
Set<Integer> starters = new HashSet<Integer>();
Set<Integer> uniqs = new HashSet<Integer>();
for (int i = 0; i < nums.length; i++) {
if (uniqs.contains(nums[i] - k)) starters.add(nums[i] - k);
if (uniqs.contains(nums[i] + k)) starters.add(nums[i]);
uniqs.add(nums[i]);
}
return starters.size();
}
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;
}