-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count of Smaller Numbers After Self
54 lines (47 loc) Β· 1.56 KB
/
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
class Solution {
public:
void merge(vector<int> &count, vector<pair<int, int> > &v, int left, int mid, int right) {
vector<pair<int, int> > tmp(right-left+1);
int i = left;
int j = mid+1;
int k = 0;
while (i <= mid && j <= right) {
// mind that we're sorting in descending order
if (v[i].first <= v[j].first) {
tmp[k++] = v[j++];
}
else {
// only line responsible to update count, related to problem constraint,
// remaining part is just regular mergeSort
count[v[i].second] += right - j + 1;
tmp[k++] = v[i++];
}
}
while (i <= mid) {
tmp[k++] = v[i++];
}
while (j <= right) {
tmp[k++] = v[j++];
}
for (int i = left; i <= right; i++)
v[i] = tmp[i-left];
}
void mergeSort(vector<int> &count, vector<pair<int, int> > &v, int left, int right) {
if (left >= right)
return;
int mid = left + (right-left)/2;
mergeSort(count, v, left, mid);
mergeSort(count, v, mid+1, right);
merge(count, v, left, mid, right);
}
vector<int> countSmaller(vector<int>& nums) {
int N = nums.size();
vector<pair<int, int> > v(N);
for (int i = 0; i < N; i++)
v[i] = make_pair(nums[i], i);
vector<int> count(N, 0);
// sorting in descending order
mergeSort(count, v, 0, N-1);
return count;
}
};