Skip to content

Commit d6ddac4

Browse files
committed
2006. Count Number of Pairs With Absolute Difference K (Hash Table)
1 parent 667d669 commit d6ddac4

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.cheehwatang.leetcode;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
// Time Complexity : O(n),
7+
// where 'n' is the length of 'nums'.
8+
// We traverse 'nums' to count the numbers in 'nums', and we traverse the HashMap with a maximum size of 'n'.
9+
//
10+
// Space Complexity : O(n),
11+
// where 'n' is the length of 'nums'.
12+
// The HashMap has a maximum size of 'n' if the numbers in 'nums' are all unique.
13+
14+
public class CountNumberOfPairsWithAbsoluteDifferenceK_HashTable {
15+
16+
// Approach:
17+
// Using a HashMap to record the frequency of occurrence for all the numbers in 'nums'.
18+
// This only add the number to the HashMap if it is in 'nums'.
19+
20+
public int countKDifference(int[] nums, int k) {
21+
22+
// Record the frequency for all the numbers into the HashMap.
23+
Map<Integer, Integer> map = new HashMap<>();
24+
for (int number : nums) {
25+
map.put(number, map.getOrDefault(number, 0) + 1);
26+
}
27+
28+
// The number of combinations is the multiples of both frequency.
29+
// e.g. [1,1,2,2,2] can have 2 * 3 = 6 combinations for k = 1.
30+
// Check for the frequency for both key - k and key + k, as the k difference can be in both directions.
31+
// Once the count is added, set the value of the number in the HashMap to 0, so that it will not be double counted.
32+
// Do note that we cannot remove the key-value pair,
33+
// as it causes Exceptions in the map.keySet() which uses an iterator.
34+
int count = 0;
35+
for (Integer key : map.keySet()) {
36+
if (map.containsKey(key - k)) {
37+
count += map.get(key) * map.get(key - k);
38+
}
39+
if (map.containsKey(key + k)) {
40+
count += map.get(key) * map.get(key + k);
41+
}
42+
map.put(key, 0);
43+
}
44+
return count;
45+
}
46+
}

0 commit comments

Comments
 (0)