-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathFindTheDistinctDifferenceArray.java
42 lines (37 loc) · 1.45 KB
/
FindTheDistinctDifferenceArray.java
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
// https://leetcode.com/problems/find-the-distinct-difference-array
// N: length of array
// T: O(N)
// S: O(N)
import java.util.HashMap;
import java.util.Map;
public class FindTheDistinctDifferenceArray {
public int[] distinctDifferenceArray(int[] nums) {
final Map<Integer, Integer> leftFrequencies = new HashMap<>();
final Map<Integer, Integer> rightFrequencies = getNumberFrequencies(nums);
final int[] result = new int[nums.length];
int k = 0;
for (int element : nums) {
addToFrequency(leftFrequencies, element);
removeFromFrequency(rightFrequencies, element);
result[k++] = leftFrequencies.size() - rightFrequencies.size();
}
return result;
}
private void removeFromFrequency(Map<Integer, Integer> frequencies, int element) {
if (frequencies.get(element) == 1) {
frequencies.remove(element);
} else {
frequencies.put(element, frequencies.getOrDefault(element, 0) - 1);
}
}
private void addToFrequency(Map<Integer, Integer> frequencies, int element) {
frequencies.put(element, frequencies.getOrDefault(element, 0) + 1);
}
private Map<Integer, Integer> getNumberFrequencies(int[] array) {
final Map<Integer, Integer> result = new HashMap<>();
for (int element : array) {
result.put(element, result.getOrDefault(element, 0) + 1);
}
return result;
}
}