# Practice25:在数组中的两个数字，如果前面一个数字大于后面的数字，则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P

55 篇文章 0 订阅
54 篇文章 0 订阅

## Practice25:

### S1

class Solution {
private:
const int kmod = 1000000007;
public:
int InversePairs(vector<int> data) {
int ret = 0;
// 在最外层开辟数组
vector<int> tmp(data.size());
merge_sort__(data, tmp, 0, data.size() - 1, ret);
return ret;
}

void merge_sort__(vector<int> &arr, vector<int> &tmp, int l, int r, int &ret) {
if (l >= r) {
return;
}

int mid = l + ((r - l) >> 1);
merge_sort__(arr, tmp, l, mid, ret);
merge_sort__(arr, tmp, mid + 1, r, ret);
merge__(arr, tmp, l, mid, r, ret);
}

void merge__(vector<int> &arr, vector<int> &tmp, int l, int mid, int r, int &ret) {
int i = l, j = mid + 1, k = 0;

while (i <= mid && j <= r) {
if (arr[i] > arr[j]) {
tmp[k++] = arr[j++];
ret += (mid - i + 1);
ret %= kmod;
}
else {
tmp[k++] = arr[i++];
}
}

while (i <= mid) {
tmp[k++] = arr[i++];
}
while (j <= r) {
tmp[k++] = arr[j++];
}

for (k = 0, i = l; i <= r; ++i, ++k) {
arr[i] = tmp[k];
}
}

};

• 0
点赞
• 1
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

07-01 832
07-09 568
09-22 29
08-22 279
09-11 299
12-03 157
08-06 344