I. Description of the 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.
Second, the method of solving problems using the idea of merging sorting, first divides the array into sub-arrays, first counts the number of reverse pairs within the subarray, and then counts the number of inverse pairs between the two adjacent sub-arrays. Note After you merge two sorted sub-arrays, you update the array.
Class Solution {Public:int inversepairs (vector<int> data) {int n=data.size (); return process (data,0,n-1); } int Process (vector<int>& data,int Start,int end) {//recursive termination condition if (start>=end) { return 0; }//merge sort, and calculate the inverse logarithm vector<int> copy (data); Array copy, for merge sort int mid= (start+end)/2; int left=process (DATA,START,MID); int right=process (data,mid+1,end); int p=mid;//p initializes the subscript int q=end;//q to the last digit of the first half, initializes the subscript int index=end;//the last digit of the second half, and initializes the subscript of the secondary array to the last int count =0;//record the number of reverse pairs while (P>=start && q>=mid+1) {if (Data[p]>data[q]) {copy[index--]=data[p--]; Count+=q-mid; } else {copy[index--]=data[q--]; }} while (P>=start) copy[index--]=data[p--]; while (Q>=mid+1) copy[index--]=data[q--]; for (int i = start; I <= end; i++) {Data[i] = copy[i];//Update Merge sorted sub-array} return (Left+right+count); }};
Classic algorithm--reverse order in the array