AcWing 65. 数组中的逆序对
原题链接
困难
作者:
adamXu
,
2020-10-08 13:09:41
,
所有人可见
,
阅读 321
class Solution {
public:
//归并模板。多写几次!!!
int merge(vector<int>& nums,int l,int r){
if(l >= r) return 0;
int mid = l + r >> 1;
int res = merge(nums,l,mid) + merge(nums,mid + 1,r);
vector<int> tmp;
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++]);
i = l;
for(auto x:tmp)
nums[i++] = x;
return res;
}
int inversePairs(vector<int>& nums) {
return merge(nums,0,nums.size() - 1);
}
};
//…nums 那里记得加引用!!!!气死我了,看了半天没看出来