描述:
https://leetcode.cn/problems/shu-zu-zhong-de-ni-xu-dui-lcof/description/
思路:
在进行归并排序时,会分成有序的左右两部分,如果左部分出现了大于右部分的数时(nums[cur1] >= nums[cur2]),那么cur1到mid的这些数就与后面的cur2组成了逆序对
代码:
class Solution {
public:int tmp[50086];int reversePairs(vector<int>& record) {return mergeSort(record, 0, record.size() - 1);}int mergeSort(vector<int> &record, int left, int right){if(left >= right) return 0;int mid = (left + right) >> 1, ret = 0;ret += mergeSort(record, left, mid);ret += mergeSort(record, mid + 1, right);int i = 0, cur1 = left, cur2 = mid + 1;while(cur1 <= mid && cur2 <= right)if(record[cur1] <= record[cur2]) tmp[i++] = record[cur1++];else ret += mid - cur1 + 1, tmp[i++] = record[cur2++];while(cur1 <= mid) tmp[i++] = record[cur1++];while(cur2 <= right) tmp[i++] = record[cur2++];for(int i = left; i <= right; i++)record[i] = tmp[i - left];return ret;}
};