AcWing 65. 数组中的逆序对
原题链接
困难
作者:
Value
,
2020-04-25 10:09:40
,
所有人可见
,
阅读 627
class Solution {
public:
typedef long long ll;
vector<int> tmp;
ll merge_sort(vector<int>& nums, int l, int r){
if(l == r) return 0;
int mid = l + r >> 1;
ll res = merge_sort(nums, l, mid) + merge_sort(nums, mid + 1, r);
int i = l, j = mid + 1;
while(i <= mid && j <= r){
if(nums[i] <= nums[j]) tmp.push_back(nums[i++]);
else{
res += mid - i + 1;
tmp.push_back(nums[j++]);
}
}
while(i <= mid) tmp.push_back(nums[i++]);
while(j <= r) tmp.push_back(nums[j++]);
int k = 0;
for(i = l; i <= r; i ++ ){
nums[i] = tmp[k++];
}
tmp.clear();
return res;
}
int inversePairs(vector<int>& nums) {
if(nums.size() == 0) return 0;
return merge_sort(nums, 0, nums.size()-1);
}
};