-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution532.java
More file actions
38 lines (32 loc) · 863 Bytes
/
Solution532.java
File metadata and controls
38 lines (32 loc) · 863 Bytes
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
26
27
28
29
30
31
32
33
34
35
36
37
38
package algorithm.leetcode;
import java.util.HashMap;
import java.util.Map;
/**
* @author: mayuan
* @desc: 数组中的K-diff数对
* @date: 2019/01/10
*/
public class Solution532 {
public int findPairs(int[] nums, int k) {
if (null == nums || 0 >= nums.length || 0 > k) {
return 0;
}
Map<Integer, Integer> map = new HashMap<>(nums.length);
for (int n : nums) {
map.put(n, 1 + map.getOrDefault(n, 0));
}
int ans = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if (0 == k) {
if (2 <= entry.getValue()) {
++ans;
}
} else {
if (map.containsKey(entry.getKey() + k)) {
++ans;
}
}
}
return ans;
}
}