题目描述:![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5761903e0039ba69d5c4398cd5dd4a3a.png)
解题思路:
- 暴力枚举,时间复杂度O(n^2)
- 归并排序,merge函数的拓展,一次处理一个区间的逆序对数量,时间复杂度O(nlogn)
代码实现:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> arr = {1, 3, 2, 5, 4, 7, 6};
int n = arr.size();
int cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
cnt++;
}
}
}
cout << "the number of reverse number pair is " << cnt << endl;
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int cnt = 0;
void Merge(vector<int>& arr, int l, int m, int r) {
int leftSize = m - l;
int rightSize = r - m + 1;
int *left = new int[leftSize];
int *right = new int[rightSize];
for (int i = l; i < m; i++) {
left[i - l] = arr[i];
}
for (int i = m; i <= r; i++) {
right[i - m] = arr[i];
}
int i = 0;
int j = 0;
int k = l;
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
cnt += (leftSize - i);
}
}
while (i < leftSize) {
arr[k++] = left[i++];
}
while (j < rightSize) {
arr[k++] = right[j++];
}
delete[] left;
left = nullptr;
delete[] right;
right = nullptr;
}
void _MergeSort(vector<int> &arr, int l, int r) {
if (l >= r) {
return;
}
int m = (r - l) / 2 + l;
_MergeSort(arr, l, m);
_MergeSort(arr, m + 1, r);
Merge(arr, l, m + 1, r);
}
void MergeSort(vector<int> &arr) {
_MergeSort(arr, 0, arr.size() - 1);
}
int main() {
vector<int> arr = {1, 3, 2, 5, 4, 7, 6};
auto f = [] (int x) {cout << x << " ";};
for_each(arr.begin(), arr.end(), f); cout << endl;
MergeSort(arr);
for_each(arr.begin(), arr.end(), f); cout << endl;
cout << "the number of reverse number pair is " << cnt << endl;
return 0;
}