Topic:
In the array of two digits, if the previous number is greater than the number that follows, then these two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in this array.
Ideas:
Merge the sort merging process. The inverse logarithm is calculated mainly considering merging two ordered sequences.
For two ascending sequences, set two subscripts: The end of the two ordered sequence. Each time the two end value is compared, if the previous end is greater than the last value, then there is a "post-sequence current length" in reverse order, otherwise it does not constitute a reverse order. The larger value is then copied to the end of the secondary array, which eventually merges two ordered sequences into the secondary array and is ordered.
In this way, each time before merging, the left and right half segments are processed recursively, then the left and right halves are ordered, and the reverse logarithm of the left-and half-segments is obtained, and then the number of reversed pairs is calculated.
Total Number = left number + right number + the number of combined
Attention:
Note that the order of the Inversepairscore parameters is (data,copy), whereas the arguments that are called recursively are (Copy,data).
To understand the function of the recursive function Inversepairscore, it is to merge the left and right halves of data and copy to the auxiliary array copy in order.
Finally, both the data and copy two arrays are ordered.
Code:
classSolution { Public: intInversepairs (vector<int>data) { if(Data.size () <=1)return 0; Vector<int>copy (data); returnInversepairscore (Data,copy,0, Data.size ()-1); }Private: intInversepairscore (vector<int> &data,vector<int> ©,intBeginintend) {//merge the two halves of data into the auxiliary array copy in orderif(begin==end) {Copy[end]=Data[end]; return 0; } Else { intmid=begin+ (End-begin)/2; intLeft=inversepairscore (Copy,data, Begin,mid);//order the left half of data intRight=inversepairscore (Copy,data, mid+1, end);//order the right half of data intCnt=0; intcpindex=end; intPre=mid; intpost=end; //Merge two ordered segments into copy array while(Pre>=begin && post>=mid+1) { if(data[pre]>Data[post])//Each comparison is two ordered sequence {cnt=cnt+ (post-mid-1+1); Copy[cpindex--]=Data[pre]; Pre--; } Else{Copy[cpindex--]=Data[post]; Post--; } } for(;p re>=begin;--pre) Copy[cpindex--]=Data[pre]; for(;p ost>=mid+1;--Post) Copy[cpindex--]=Data[post]; returnleft+right+CNT; } }};
"The point of the sword" question 36: reverse order in an array