4. Median of Sorted Arrays

Source: Internet
Author: User

1, Median of two Sorted arrays--This is the fourth question of Leedcode:
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)).
The title is simple, with two sequential sequences, to find out the median of the two sequential sequences combined. Time complexity requirements O (log (m+n));
Solution Ideas:
1. Habitual thinking (wrong):
Using sorting to combine two arrays into an array, and then returning the median, if you use this algorithm, the time complexity is O (m+n) and does not meet the requirements.
2. Correct ideas:
This idea is not what I think of myself, but what I see in the discussion area. Here is summarized as follows:
A, here the two series named A, B;
b, the two sequences are divided into the left and right two parts named Left_part and Right_part respectively:

 Left_part | Right_parta[0 ], A[1 ],  , A[i-1 ] | A[i], A[i+1 ],  ... , a[m- 1 ] B[0 ], B[1 ],  ...  , B[j-1 ] | B[J], B[j+1 ],  ... , b[n- 1 ]  

C, if we can ensure the following two conditions, we can divide two sequences into two parts;
1) len (left_part) = = Len (right_part) The left length equals the right length
2) Max (Left_part) <= min (Right_part) to the left of the largest number, less than equals to the right of the smallest number.
Just
(1) i + j = = M-i + n-j (or: M-i + n-j + 1)
If n >= m, simplify the above formula, you can get: when i = 0 ~ m, j = (m + n + 1)/2-i
(2) b[j-1] <= a[i] and a[i-1] <= B[j]
D, after getting the formula above, it is clear to find that I, so as to get the median. But the complexity of time did not meet the requirements. Considering that two sequences are ordered separately, we can use a binary search so that the time complexity can be achieved.

<1> Make imin =0, Imax = m, and then in[Imin, Imax]Find inI<2> OrderI= (Imin + IMAX)/2,J= (m + n +1)/2-I<3> Can meet Len (left_part) ==len (Right_part) at this time. In the process of finding, the following three scenarios occur: <a> B[J1]<= A[i]and A[i1]<= B[j]If that's the case, it means we found the one.I, stop looking; <b> b[J1]> A[i]means a.[i]It's too small to be adjusted.I, thus getting B[J1]<= A[i]; There needs to be an increaseIBecauseJAndIis anti-related,IIncreaseJis reduced. So we need to adjustIRange of changes from[i+1, Imax].So set imin =I+1, Jump to <2> Continue execution. <c> A[i1]> B[j]means a.[i1]Too big, in the same way, needs to be reducedIValue, so that a[i1]<=b[j]Meet, so adjust the look range to[Imin, I1]。 Set Imax =I-1, Jump to <2> Continue execution.

E, this time, we need to solve, is the boundary condition problem, when i=0/i=m/j=0/j=n, a[i-1],b[j-1],a[i],b[j] These values are boundary values. And we can simply pass judgment to know where the median is. At this point, the idea has been very clear.
The code for the accept is posted here:
Java version:

public class Solution {publicDoubleFindmediansortedarrays (int[] nums1,int[] nums2) {intSize1 = nums1.length, Size2 = Nums2.length;int Max,min;intI, J;intMax_of_left, Min_of_right;intHalflength = (size1 + size2 +1) /2;//If the nums length is greater than NUMS2, swap        if(Size1 > Size2) {inttemp = size1;            Size1 = Size2; Size2 = temp;int[] Temparray = NUMS1;            NUMS1 = NUMS2;        NUMS2 = Temparray; }min=0;Max= Size1;//Below are two-point search         while(min<=Max) {i = (min+Max) /2; j = halflength-i;if(I < size1 && J >0&& Nums1[i] < nums2[j-1]) {The first two conditions are to ensure that the boundary value is not reached, and when nums1[i]<nums2[j-1] is increased, the find lower limit                min= i +1; }Else if(J < size2 && i >0&& Nums2[j] < nums1[i-1]) {The first two conditions are to ensure that the boundary value is not reached, and when nums2[j]<nums1[i-1] is lowered, the search limit is reduced                Max= i-1; }Else{//Find this I, meet the conditions, can get the median                // *************************//                //The following is the judgment of the boundary value                if(i = =0) {Max_of_left = Nums2[j-1]; }Else if(J = =0) {Max_of_left = Nums1[i-1]; }Else{//Otherwise, the largest number of the two is the largest number on the leftMax_of_left = Nums1[i-1] > Nums2[j-1] ? Nums1[i-1]: Nums2[j-1]; }//If the sum of the two is odd, because to ensure the same length on both sides , that is                //i + j = = M-i + n-j or i + j = = M-i + n-j + 1                //Here Set Halflength = (size1 + size2 + 1) 2;                //So if both and is odd, then one more number on the left than the right, the median on the left, and the largest.                 if((size1 + size2)%2==1) {returnMax_of_left; }if(i = = size1)                {min_of_right = nums2[j]; }Else if(j = = Size2)                {min_of_right = Nums1[i]; }Else{min_of_right = Nums1[i] < Nums2[j]? Nums1[i]: Nums2[j]; }return((float) (Max_of_left + min_of_right))/2; }        }return 0; }}

C + + version:

classSolution { Public:DoubleFindmediansortedarrays ( vector<int>& Nums1, vector<int>& Nums2) {intm = Nums1.size (), n = nums2.size ();if(m>n) {returnFindmediansortedarrays (NUMS2, NUMS1); }intMin =0Iintmax = m, J;intHalflength = (m + n +1) >>1; while(min <= max) {i = (min + max) >>1; j = halflength-i;if(J >0&& i < M&&nums1[i] < nums2[j-1]) {min = i +1; }Else if(I >0&& J < N&&nums2[j] < nums1[i-1]) {max = i-1; }Else{intMaxofleft;if(i==0) {Maxofleft = Nums2[j-1]; }Else if(j==0) {Maxofleft = Nums1[i-1]; }Else{maxofleft = nums1[i-1] > Nums2[j-1] ? Nums1[i-1]: Nums2[j-1]; }if((m+n)%2==1)                {returnMaxofleft; }intMinofright;if(i==m)                {minofright = nums2[j]; }Else if(j==n)                {minofright = Nums1[i]; }Else{minofright = Nums1[i] < Nums2[j]? Nums1[i]: Nums2[j]; }return((float) Minofright + maxofleft)/2; }        }return 0; }};

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.