315 Count of Smaller Numbers After Self

題目:
https://leetcode.com/problems/count-of-smaller-numbers-after-self/

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
// 一個更好的解法是Fenwick Tree (Binary Indexed Tree BIT),這邊用歸併分治
class Solution {
public:
vector<int> arr, help, ans, idx, help_idx;

vector<int> countSmaller(vector<int>& nums) {
int size = nums.size();

arr.assign(size, 0);
help.assign(size, 0);
ans.assign(size, 0);
idx.assign(size, 0);
help_idx.assign(size, 0);

for(int i=0; i<size; ++i){
arr[i] = nums[i];
idx[i] = i;
}
merge(0, size-1);

return ans;
}

void merge(int l, int r){
if (l >= r) return; // l shouldn't be greater than r, and return when l == r

int m = l + (r-l)/2; // prevent overflow
merge(l, m);
merge(m+1, r);
solve(l, m, r);
}

void solve(int l, int m, int r){
// count
for(int i=l, j = m+1; i<=m; ++i){
while(j <= r && arr[i] > arr[j]){
j++;
}
ans[idx[i]] += (j-(m+1)); // total count = end - begin
}

// sort
int i = l;
int a = l;
int b = m+1;
while(a <= m && b <= r){
if(arr[a] <= arr[b]){
help_idx[i] = idx[a];
help[i++] = arr[a++];
}
else{
help_idx[i] = idx[b];
help[i++] = arr[b++];
}
}
while(a <= m){
help_idx[i] = idx[a];
help[i++] = arr[a++];
}
while(b <= r){
help_idx[i] = idx[b];
help[i++] = arr[b++];
}
for(int k=l; k <= r; ++k){
arr[k] = help[k];
idx[k] = help_idx[k];
}
}
};