Title Descriptionin 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 p. and the output of p to 1000000007 modulo is obtained. i.e. Output p%1000000007
"Thinking" to see such a topic, the simplest idea is to traverse each element, so that it is compared with the following elements, if greater than the count++, but such a time complexity is O (N2), according to the topic given the amount of data, it is obvious time-out. So think of the idea of merging sort.
1 classSolution {2 Public:3 voidMergecount (vector<int>& data,intBeginintMidintEndint&count)4 {5 inti = begin, J =mid;6 intTemp[end-begin], k =0;7 while(I < mid && J <end)8 {9 if(Data[i] <Data[j])Ten { Onetemp[k++] = data[i++]; A } - Else - { theCount + = mid-i; - if(Count >1000000007) Count%=1000000007; -temp[k++] = data[j++]; - } + } - while(I < mid) temp[k++] = data[i++]; + while(J < end) temp[k++] = data[j++]; A for(ints =0; s < End-begin; ++s) Data[s + begin] =Temp[s]; at } - voidMergeSort (vector<int>& data,intBeginintEndint&count) - { - if(Begin +1= = end)return; - intMID = (begin + END)/2; - mergesort (data, begin, Mid,count); in mergesort (data, mid, end, count); - mergecount (data, begin, mid, end, count); to } + intInversepairs (vector<int>data) - { the intn = static_cast<int>(Data.size ()); * if(n = =0|| n = =1)return 0; $ intCount =0;Panax NotoginsengMergeSort (data,0, N, Count); - returncount; the } +};
[Sword means offer] 35. Reverse order in the array