"Sword Point offer" topic 36 reverse order in the array

Source: Internet
Author: User

Any of the two numbers in the array, if the preceding number is greater than the number that follows, is called an inverse

For example: 1,2,1,2,1 has 3 reverse

Idea: Knowing O (N2) must be wrong. Start to think hash, try to find O (n) algorithm, think for a long time, can not find. Later thought of the sort, with the original array and the array of arrays compared, I write the quick row, or not. Thought for a few hours, helpless to see the answer, the original is a transformation of the merger sort. The sort is so profound, I can't think of it in a different way ....

On the cattle online AC code: The brain is not awake, a variety of small mistakes, submitted many times.

classSolution { Public:    voidMymergesort (vector<int> &data,int& ans,intLintR, vector<int> &v) {if(L >= R)return; intm = L + (r-l)/2;        Mymergesort (data, ans, l, M, v); Mymergesort (data, ans, M+1, R, v);              Mymerge (data, ans, L, M, R, v); }    voidMymerge (vector<int> &data,int& ans,intLintMintR, vector<int> &v) {intN1 = M-l +1; intK =0, i = l, j = m +1;  while(I <= m && J <=r) {if(Data[i] <=Data[j]) {V[k+ +] = data[i++]; }            Else{v[k+ +] = data[j++]; Ans+ = M-i +1; }        }         while(I <=m) v[k+ +] = data[i++];  while(J <=r) V[k+ +] = data[j++];  for(k =0; K < R-l +1; k++) Data[k+ L] =V[k]; }    intInversepairs (vector<int>data) {        intAns =0; Vector<int>V (data.size ()); Mymergesort (data, ans,0, Data.size ()-1, V); returnans; }};

"Sword Point offer" topic 36 reverse order in the array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.