-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCount Smaller elements
46 lines (39 loc) Β· 1.03 KB
/
Count Smaller elements
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
class Solution {
private:
vector<int> BIT;
int n;
void update(int index, int val) {
index++;
while (index <= n) {
BIT[index] += val;
index += index & (-index);
}
}
int query(int index) {
int sum = 0;
index++;
while (index > 0) {
sum += BIT[index];
index -= index & (-index);
}
return sum;
}
public:
vector<int> constructLowerArray(vector<int>& arr) {
n = arr.size();
BIT.resize(n + 1, 0);
vector<int> sortedArr = arr;
sort(sortedArr.begin(), sortedArr.end());
unordered_map<int, int> valueToIndex;
for (int i = 0; i < n; i++) {
valueToIndex[sortedArr[i]] = i;
}
vector<int> result(n);
for (int i = n - 1; i >= 0; i--) {
int index = valueToIndex[arr[i]];
result[i] = query(index - 1);
update(index, 1);
}
return result;
}
};