没想到一个简单的归并排序,也要这么久,足足写了一个小时25分钟,才能验证通过
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。
输入:
1,2,3,4,5,6,7,0
输出:
7
类似与归并排序,代码中的start和end都是左闭右开区间,比如说【0,2),这个就代表了元素{1,2};
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Solution { public: int InversePairs(vector<int> data) { if (data.size() <= 1) { return 0; } int start= 0; int end = data.size(); return mergeVector(&data, start, end); } private: int mergeVector(vector<int>* vec, int start, int end); }; int Solution::mergeVector(vector<int>* vec, int start, int end) { if (end - start > 2) { const int middle = start + (end - start)/2; int startCount = mergeVector(vec, start, middle); int endCount = mergeVector(vec, middle, end); int sum = 0; int startEndPointer = middle - 1; int endEndPointer = end - 1; int *array = new int[end - start]; int arrayPointer = end - start - 1; //把两个从小到大排列的数组合并为一个数组 while (endEndPointer >= middle) { while (((*vec)[startEndPointer] > (*vec)[endEndPointer]) && startEndPointer >= start) { //逆序的部分元素个数如(5,6)(0,7),此事middle指向0,endEndPointer也只向0 sum += endEndPointer - middle + 1; //题目要求结果需要对1000000007求余 sum %= 1000000007; array[arrayPointer--] = (*vec)[startEndPointer--]; //cout<<"startEndPointer = "<<startEndPointer + 1<<endl; } array[arrayPointer--] = (*vec)[endEndPointer]; endEndPointer--; //cout<<"endEndPointer = "<<endEndPointer + 1<<endl; } //第一个数组可能还会剩下元素 while (startEndPointer >= start) { array[arrayPointer--] = (*vec)[startEndPointer--]; } //cout<<"start merge: "<<endl; for (int i = start; i < end ;i++) { (*vec)[i] = array[i - start]; //cout<<i<<" "<<(*vec)[i]<<endl; } sum += startCount + endCount; //题目要求结果需要对1000000007求余 sum %= 1000000007; delete array; return sum; } if (end - start == 2) { if ((*vec)[start] > (*vec)[end - 1]) { /*int temp = (*vec)[start]; (*vec)[start] = (*vec)[end - 1]; (*vec)[end - 1] = temp;*/ swap((*vec)[start], (*vec)[end -1]); return 1; } } return 0; } int main() { int array[] = {1,2,3,4,5,6,7,0}; vector<int> vec(array, array + 8); /*for (vector<int>::iterator it = vec.begin();it != vec.end(); it++) { cout<<*it<<endl; }*/ cout<<Solution().InversePairs(vec); return 0; }