计算右侧小于当前元素的个数
class Solution {
public:
void merge_sort(vector<pair<int, int>>& Vec, vector<int> &count)
{
if (Vec.size()<2)
return;
int low = 0;
int high = Vec.size() - 1;
int mid = (low+high) / 2;
vector<pair<int, int>> sub_vec1;
vector<pair<int, int>> sub_vec2;
for (int i = 0; i<Vec.size(); ++i)
{
if (i <= mid)
{
sub_vec1.push_back(Vec[i]);
}
else
sub_vec2.push_back(Vec[i]);
}
//然后进入两个子序列中进行计算,出来后需要进行排序操作。
merge_sort(sub_vec1, count);
merge_sort(sub_vec2, count);
int p1 = sub_vec1.size() - 1;
int p2 = sub_vec2.size() - 1;
int K = Vec.size() - 1;
while (p1 >= 0 && p2 >= 0)
{
if (sub_vec1[p1].first > sub_vec2[p2].first)
{
Vec[K] = sub_vec1[p1];
count[sub_vec1[p1].second] += p2+ 1;
--p1;
--K;
}
else
{
Vec[K] = sub_vec2[p2];
--p2;
--K;
}
}
for (; p1 >= 0; --p1)
{
Vec[K] = sub_vec1[p1];
--K;
}
for (; p2 >= 0; --p2)
{
Vec[K] = sub_vec2[p2];
--K;
}
}
vector<int> countSmaller(vector<int>& nums) {
//使用归并排序算法的原理
//我们需要使用pair
vector<pair<int, int>> Vec;
vector<int> count;
for (int i = 0; i<nums.size(); ++i)
{
Vec.push_back(make_pair(nums[i], i));
count.push_back(0);
}
merge_sort(Vec, count);
return count;
}
};