-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
66 lines (52 loc) · 1.51 KB
/
Copy pathsolution.cpp
File metadata and controls
66 lines (52 loc) · 1.51 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
class Solution
{
public:
// Binary search to find first index >= target
int lowerBound(vector<int> &positions, int target)
{
int low = 0;
int high = positions.size();
while (low < high)
{
int mid = low + (high - low) / 2;
if (positions[mid] < target)
low = mid + 1;
else
high = mid;
}
return low;
}
vector<int> freqInRange(vector<int> &arr, vector<vector<int>> &queries)
{
// Store all occurrence positions of every value
unordered_map<int, vector<int>> mp;
for (int i = 0; i < arr.size(); i++)
{
mp[arr[i]].push_back(i);
}
vector<int> ans;
for (auto &q : queries)
{
int l = q[0];
int r = q[1];
int x = q[2];
// If value never appeared
if (!mp.count(x))
{
ans.push_back(0);
continue;
}
vector<int> &positions = mp[x];
// First occurrence >= l
int left = lowerBound(positions, l);
// First occurrence > r
int right = upper_bound(
positions.begin(),
positions.end(),
r) -
positions.begin();
ans.push_back(right - left);
}
return ans;
}
};