forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindTargetIndicesAfterSortingArray.java
35 lines (31 loc) · 1.08 KB
/
FindTargetIndicesAfterSortingArray.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
// https://leetcode.com/problems/find-target-indices-after-sorting-array
// T: O(|nums|)
// S: O(|nums|)
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FindTargetIndicesAfterSortingArray {
public List<Integer> targetIndices(int[] nums, int target) {
final Map<Integer, Integer> frequency = getFrequency(nums);
int index = 0;
for (int i = 0 ; i < target ; i++) {
index += frequency.getOrDefault(i, 0);
}
return indices(index, frequency.getOrDefault(target, 0));
}
private Map<Integer, Integer> getFrequency(int[] array) {
final Map<Integer, Integer> result = new HashMap<>();
for (int element : array) {
result.put(element, result.getOrDefault(element, 0) + 1);
}
return result;
}
private List<Integer> indices(int start, int length) {
final List<Integer> result = new ArrayList<>(length);
for (int i = 0 ; i < length ; i++) {
result.add(start++);
}
return result;
}
}