使用归并算法求逆序数
程序员文章站
2024-03-15 17:46:12
...
#include<iostream>
#include<vector>
#include <algorithm>
#include<iomanip>
#include<string>
using namespace std;
class Solution {
public:
long long nums = 0;
int InversePairs(vector<int> data) {
vector<int> temp=data;
MSort(data, temp, 0, data.size()-1);
// cout << "nums:" << nums << endl;
return nums % 1000000007;
}
void Merge(vector<int> &data, vector<int> &temp, int begin, int mid, int end)
{
int start = begin;//记录开始位置
int left = begin;
int right = mid + 1;
while (left<=mid && right <=end)
{
if (data[left] < data[right])
{
temp[begin++] = data[left++];
}
else
{
temp[begin++] = data[right++];
nums += mid - left + 1;
}
}
while (left<=mid)
{
temp[begin++] = data[left++];
}
while (right <= end)
{
temp[begin++] = data[right++];
}
while (start<=end)
{
data[start] = temp[start];
start++;
}
}
void MSort(vector<int> &data, vector<int> &temp, int begin,int end)
{
int mid;
if (begin < end)
{
mid = (begin + end) / 2;
MSort(data, temp, begin, mid);
MSort(data, temp, mid+1,end);
Merge(data, temp, begin, mid, end);
}
}
};
int main()
{
vector<int> data = { 1,2,3,4,5,6,7,0 };
Solution so;
so.InversePairs(data);
return 0;
}
上一篇: js对象 js
下一篇: C++笔记(四)——类和对象Ⅰ