-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKdiffPairsinanArray.java
More file actions
39 lines (34 loc) · 953 Bytes
/
KdiffPairsinanArray.java
File metadata and controls
39 lines (34 loc) · 953 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
39
package easy;
import java.util*;
/**
* ClassName: KdiffPairsinanArray.java
* Author: chenyiAlone
* Create Time: 2019/1/3 21:43
* Description: No.532 K diff Pairs in an Array
*/
public class KdiffPairsinanArray {
public int findPairs(int[] nums, int k) {
int ret = 0;
if (k < 0)
return ret;
Map<Integer, Integer> map = new HashMap<>();
for (int i : nums)
map.put(i, map.containsKey(i) ? map.get(i) + 1 : 1);
Iterator<Integer> iter = map.keySet().iterator();
while (iter.hasNext()) {
int i = iter.next();
if (k == 0) {
if (map.get(i) > 1) ret++;
} else {
if (map.containsKey(i - k)) {
ret++;
}
if (map.containsKey(i + k)) {
ret++;
}
}
iter.remove();
}
return ret;
}
}