"Leetcode" Median of the Sorted Arrays (hard) ★!!

Source: Internet
Author: User

There is sorted arrays A and B of size m and N respectively. Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).

Ideas:

Difficult, know to divide the algorithm, but do not know how to use. Had to look at the answer.

The basic idea is if the median is the number of K, a[i] If the median, then a[i] is greater than the number of I, but also greater than k-i-1 numbers and b[k-i-2] contrast. But if the median is not in a, my brain is dizzy. Here is the big God code, I still do not understand.

classSolution { Public:    DoubleFindmediansortedarrays (intA[],intMintB[],intN) {//The following call was to make sure Len (A) <= len (B). //Yes, it calls itself, but at the most once, shouldn ' t is//consider a recursive solution        if(M >N)returnfindmediansortedarrays (B, N, A, M); DoubleAns =0; //Now , do binary search        intK = (n + M-1) /2; intL =0, r = min (k, m);//R is N, not n-1, the is important!!         while(L <r) {intMidA = (L + r)/2; intMidB = k-MidA; if(A[mida] <B[midb]) L= MidA +1; ElseR=MidA; }        //After binary search, we almost get the median because it must be between//these 4 numbers:a[l-1], a[l], b[k-l], and b[k-l+1]//if (n+m) is odd, the median is the larger one between A[L-1] and B[k-l]. //And There is some corner cases we need to take care of.        intA = max (L >0? A[l-1] : -(1<< -), K-L >=0? B[K-L]:-(1<< -)); if(((n + m) &1) ==1)            return(Double) A; //if (n+m) is even, the median can being calculated by//median = (max (a[l-1], b[k-l]) + min (a[l], b[k-l+1])/2.0//Also, there is some corner cases to take care of.        intb = min (L < m?) A[l]: (1<< -), K-L +1< n? B[k-l +1] : (1<< -)); return(A + B)/2.0; }};

"Leetcode" Median of the Sorted Arrays (hard) ★!!

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.