-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
73 lines (54 loc) · 1.78 KB
/
Copy pathsolution.java
File metadata and controls
73 lines (54 loc) · 1.78 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Solution {
public ArrayList<Integer> freqInRange(int[] arr, int[][] queries) {
// Store occurrence positions of every value
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
map.putIfAbsent(arr[i], new ArrayList<>());
map.get(arr[i]).add(i);
}
ArrayList<Integer> ans = new ArrayList<>();
for (int[] q : queries) {
int l = q[0];
int r = q[1];
int x = q[2];
// Value not present in array
if (!map.containsKey(x)) {
ans.add(0);
continue;
}
ArrayList<Integer> positions = map.get(x);
// First position >= l
int left = lowerBound(positions, l);
// First position > r
int right = upperBound(positions, r);
ans.add(right - left);
}
return ans;
}
// Finds first index >= target
private int lowerBound(ArrayList<Integer> list, int target) {
int low = 0;
int high = list.size();
while (low < high) {
int mid = low + (high - low) / 2;
if (list.get(mid) < target)
low = mid + 1;
else
high = mid;
}
return low;
}
// Finds first index > target
private int upperBound(ArrayList<Integer> list, int target) {
int low = 0;
int high = list.size();
while (low < high) {
int mid = low + (high - low) / 2;
if (list.get(mid) <= target)
low = mid + 1;
else
high = mid;
}
return low;
}
}