The title describes the two numbers in the array, and if the previous number is greater than the number that follows, the two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in this array. Analysis: Using the idea of merge sorting, divided into 2 parts, each part according to from the big to the small sort, then compares the left side of the a[i] and the right side of the b[j] if A[I]>B[J], then a[j] greater than b[j]~b[right], to produce right-j+1 group reverse order. If A[J]<=B[J], do not produce reverse order. It also updates the left-to-right part of the array, sorts it from the large to the small, and then sorts the array with the sort number and the larger array, while calculating the number of reverse groups.
classSolution {Private: intMerge (vector<int>& data,intLeftintMidintRight ) {Vector<int>Tmpvec; intCNT =0; inti = left, J = mid +1; //sort Vecotr from big to small while(I <= mid && J <=Right ) { if(Data[i] >Data[j]) {CNT+ = (Right-j +1); Tmpvec.push_back (Data[i]); I++; } Else{tmpvec.push_back (data[j]); J++; } } while(I <=mid) {tmpvec.push_back (data[i]); I++; } while(J <=Right ) {Tmpvec.push_back (data[j]); J++; } //copy TMP data to original data for(intK =0; K <= (Right-left); k++) {data[k+ Left] =Tmpvec[k]; } returnCNT; } intInversepairs (vector<int>& data,intLeftintRight ) { if(data.size () = =0) return 0; if(Left >=Right )return 0; intMid = (left + right)/2; intCNT =0; CNT+=inversepairs (data, left, mid); CNT+ = Inversepairs (data, Mid +1, right); CNT+=merge (data, left, Mid, right); returnCNT; } Public: intInversepairs (vector<int>data) { returnInversepairs (data,0, Data.size ()-1); }};
[The Order of the sword] the reverse order in the array