The following method works even if the array contains duplicates. It implements Pshemo's final algorithm (without the duplicate work and without the division by 2).
First, it stores the contents of the original array in a hashmap. The original value is the key, and the number of times the original value appears in the array is the value of the hashmap. This phase has a runtime O(number of items in the original list), and uses storage O(number of distinct items in the original list).
Second, it loops through the hashmap, and finds any items that are (delta = 4
) greater than the item being considered. It does some math to increment the result tally. It has a special case to handle (delta == 0
) scenarios, to deal with the issue Ling Zhong mentioned. This phase has a runtime O(number of distinct items in the original list).
public class Solution {
public int countDifferences(int delta, int[] array) {
if (array == null) {
return 0;
}
// Load the contents of the array into a hashmap.
// This process loses the sorting.
HashMap<Integer, Integer> choices = new HashMap<>();
for (int arrayItem : array) {
if (choices.containsKey(arrayItem)) {
choices.put(arrayItem, 1 + choices.get(arrayItem));
} else {
choices.put(arrayItem, 1);
}
}
// Count the result.
int result = 0;
for(Map.Entry<Integer, Integer> e : choices.entrySet()) {
Integer key = e.getKey();
Integer value = e.getValue();
if (delta == 0) {
result += value * (value - 1) / 2; // add summorial(value - 1)
} else {
if (choices.containsKey(key + delta)) {
result += value * choices.get(key + delta);
}
}
}
return result;
}
}