剑指OFFER----面试题51. 数组中的逆序对
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
代码
class Solution {
public:
int merge_sort(int l, int r, vector<int>& nums) {
if (l >= r) return 0;
int mid = l + r >> 1;
int res = merge_sort(l, mid, nums) + merge_sort(mid + 1, r, nums);
int i = l, j = mid + 1, k = 0, help[nums.size() + 1];
while (i <= mid && j <= r) {
if (nums[i] <= nums[j]) {
help[k++] = nums[i++];
} else {
res += mid - i + 1;
help[k++] = nums[j++];
}
}
while (i <= mid) help[k++] = nums[i++];
while (j <= r) help[k++] = nums[j++];
for (i = l, j = 0; i <= r; i++, j++) nums[i] = help[j];
return res;
}
int reversePairs(vector<int>& nums) {
int res = 0;
return merge_sort(0, nums.size() - 1, nums);
}
};