题目要求:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
分析:使用归并排序中分治思想,先将数组中数字递归划分,然后再合并进行排序同时统计逆序数。
class Solution {
public:
int reverseCount = 0;
int reversePairs(vector<int>& nums) {
if(nums.empty())
return 0;
vector<int> copy(nums.size(),0);
merge_sort(nums,copy,0,nums.size()-1);
return reverseCount;
}
void merge_sort(vector<int> &nums,vector<int> ©,int left,int right) {
if(left >= right)
return;
int mid = (left + right) / 2;
merge_sort(nums,copy,left,mid);
merge_sort(nums,copy,mid+1,right);
Merge(nums,copy,left,mid,right);
}
void Merge(vector<int> &nums,vector<int> ©,int left,int mid,int right) {
int i = left;
int j = mid + 1;
int k = 0;
while(i <= mid && j <= right) {
if(nums[i] <= nums[j]) {
copy[k++] = nums[i++];
}
else {
copy[k++] = nums[j++];
reverseCount += mid-i+1;
}
}
while(i <= mid)
copy[k++] = nums[i++];
while(j <= right)
copy[k++] = nums[j++];
k = 0;
while(left <= right) {
nums[left++] = copy[k++];
}
}
};