-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathKDiffPairs.java
More file actions
52 lines (45 loc) · 1.36 KB
/
KDiffPairs.java
File metadata and controls
52 lines (45 loc) · 1.36 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
// O(n^2) time, O(n) space
// class Solution {
// public int findPairs(int[] nums, int k) {
// Set<List<Integer>> set = new HashSet<>();
// int count = 0;
// for (int i = 0; i < nums.length; i++) {
// for (int j = i+1; j < nums.length; j++) {
// if (Math.abs(nums[i] - nums[j]) == k) {
// int a = Math.min(nums[i], nums[j]);
// int b = Math.max(nums[i], nums[j]);
// if (set.add(Arrays.asList(a, b))) {
// count++;
// }
// }
// }
// }
// return count;
// }
// }
// O(n) time, O(n) space
class Solution {
public int findPairs(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int count = 0;
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
int num = e.getKey();
int freq = e.getValue();
if (k == 0) {
if (freq >= 2) {
count++;
}
}
if (k > 0) {
if (map.containsKey(num + k)) {
count++;
}
}
}
return count;
}
}