4. Median of Sorted Arrays

Source: Internet
Author: User

There is sorted arrays nums1 and nums2 of size M and N respectively.

Find The median of the sorted arrays. The overall run time complexity should be O (log (m+n)).

Example 1:

NUMS1 = [1, 3]nums2 = [2]the median is 2.0

Example 2:

NUMS1 = [1, 2]NUMS2 = [3, 4]the median is (2 + 3)/2 = 2.5

==============

Find the median of two arrays,

The definition of the median is clear: the ordered array, array.size=n is an odd number, (n+1)/2 digits; otherwise it is the average of N/2 and (n+1)/2.

========== ideas:

Division of Ideas,

The first step: follow the merge idea to find two in the array of K-large

The second step is to return the median by the method of calculating the median number.

=========

Code implementation,

classSolution { Public:    DoubleFindmediansortedarrays (vector<int>& Nums1, vector<int>&nums2) {        intLengtha =nums1.size (); intLENGTHB =nums2.size (); intTotal = lengtha+LENGTHB; if(Total &0x1){            returnFind_kth (nums1,nums2,total/2+1); }Else{            return(Find_kth (nums1,nums2,total/2)+find_kth (Nums1,nums2,total/2+1))/2.0; }    }Private:    intFind_kth (vector<int> &A,vector<int> &b,intk) {std::vector<int>::const_iterator P1 =A.begin (); Std::vector<int>::const_iterator P2 =B.begin (); intm =0;  while(P1!=a.end () && p2!=B.end ()) {            if(*p1<=*p2 && m== (K-1)){                return*P1; }Else if(*p1>*p2 && m== (K-1)){                return*P2; }            if(*p1<=*p2) P1++; ElseP2++; M++; }// while         while(p1!=A.end ()) {            if(m== (K-1)){                return*P1; } p1++; M++; }         while(p2!=B.end ()) {            if(m== (K-1)){                return*P2; } P2++; M++; }        return-1; }};

4. Median of Sorted Arrays

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.