Count Number of Pairs With Absolute Difference K LeetCode solution in Java

1
class Solution {
2
public int countKDifference(int[] nums, int k) {
3
Map<Integer, Integer> map = new HashMap<>();
4
int res = 0;
5

6
for (int i = 0; i < nums.length; i++) {
7
if (map.containsKey(nums[i] - k)) {
8
res += map.get(nums[i] - k);
9
}
10
if (map.containsKey(nums[i] + k)) {
11
res += map.get(nums[i] + k);
12
}
13
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
14
}
15

16
return res;
17
}
18
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0