AcWing 65. 数组中的逆序对
原题链接
困难
作者:
Value
,
2020-05-27 10:30:30
,
所有人可见
,
阅读 465
class Solution {
public:
int inversePairs(vector<int>& nums) {
// 特判空数组
if(nums.size() == 0) return 0;
return merge_sort(nums, 0, nums.size() - 1);
}
int merge_sort(vector<int>& nums, int l, int r){
if(l == r) return 0;
int mid = l + r >> 1;
long long res = merge_sort(nums, l, mid) + merge_sort(nums, mid + 1, r);
vector<int> backup(r - l + 10);
int i, j, k;
i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r){
if(nums[i] <= nums[j]) backup[k ++ ] = nums[i ++ ];
else{
res += mid - i + 1;
backup[k ++ ] = nums[j ++ ];
}
}
while(i <= mid) backup[k ++ ] = nums[i ++ ];
while(j <= r) backup[k ++ ] = nums[j ++ ];
for(i = l, k = 0; i <= r; i ++ ) nums[i] = backup[k ++ ];
return res;
}
};