[Leetcode] 4. Median of two sorted arrays

Source: Internet
Author: User
Tags array length

The difficulty rating of the problem is hard, so where is the difficult? Let's look at the topic first.

Given two ordered arrays of size m and n nums1 and nums2 .

Please find out the median of these two ordered arrays. The time complexity required for the algorithm is O (log (m+n)).

Example 1:

NUMS1 = [1, 3]NUMS2 = [2] median is 2.0

Example 2:

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

What do you think of when you see that the required time complexity is O (log (m+n))? Yes, the dichotomy.

As seen from the example, if the length of the two array is odd, the median is the number in the middle of the size, and if the length of the two array is even, then the median is the average of two numbers in the middle of the size.

It seems that we need to classify the discussion, and consider some corner case to complete the solution, then there is no more ingenious method? Yes, I have said so, there must be some.

The following solution is the official website community discussion group inside the solution of a great God, I come to carry over to translate, help me to understand, but also help the person who has doubts.

Original Post:https://leetcode.com/problems/median-of-two-sorted-arrays/discuss/2471/very-concise-o (min (MN)))- Iterative-solution-with-detailed-explanation

Don't say much, let's start to see how the Great God is loaded.

This solution requires a mindset shift, can we think of both the length and the odd and the long and the even numbers as the same situation? yes!

First, let's look at the concept of the median:

If we cut an ordered array into 2 equal-length parts, the median is the minimum value of the first half and the second half, both and the average.

Don't you get it? No problem, for example: for [2 3 5 7] This array, we cut a knife in the middle of 3 and 5 (yes, that's the red slash)

[2 3 / 5 7]

Then the median median = (3+5)/2. we'll use it in the back . '/' represents a Shard,(number/number) represents a cut in the middle of a number (well, the result is one I become two me)

for arrays [2 3 4 5 6], we can slice like this, put 4 all two:

[2 3 (4/4) 5 7]

Since we cut 4 into 2 parts, the first and second half of the array contain 4. So what's the median number? Median = (4 + 4)/2 = 4; The answer is still right.

OK, now for the sake of convenience, we use L to represent the first element on the left of the cut, and R to represent the first element on the right side of the cut.

That is, for an array that has been cut by a knife [2 3/5 7], in this case, L = 3, R = 5.

So we can observe that for an ordered array of length n, the array of L and R is labeled as follows:

  N (array length) L/R corresponding array subscript 1 0/02 0/13 1/1 4 1/2 5 2/26 2/37 3/38 3/4           

It is not difficult to find, Indexl = (N-1)/2 and INDEXR = N/2. So according to the previous analysis, for any one of the array A, where the number of bits median =(L + R)/2 = (A[(N-1)/2] + A[N/2])/2 。

Before looking down, please make sure that you are fully aware of the no rag.

OK, let's go on. Now let's talk about two arrays, and we need to think of some # (pound) in the array, which wraps up the numbers in each of the arrays, and whether it's "#" or the number we call a position.

[6913[#]6 #9 #13 ##] (N =4) Position Index012345678 (n_position =9)A total of 9 position[6 9   18]-> [# 6 # 9 # One # # 5 #  ] (N = ) position index 
                                  
                                   0 
                                   1 2 3 4 5 6 7 8 9 x (n_position = 11) Total 11 Position 
                                  

You can see that no matter how much N is, there will be a 2*n+1 ' positions '. So, whether n is odd or even, from position's point of view, assuming that the first position subscript is 0, then to cut a knife in the middle, it must be in the nth position (this is called cutposition).

As we have concluded in an array of index (l) = (N-1)/2, index (r) = N/2, we further conclude index (l) = (CutPosition-1)/2, index (r) = (cutposition)/2 .

Similarly, before looking down, please make sure that you are fully aware of the no rag.

Well, let's continue, for the case of 2 arrays,

1 # 2 # 3 # 4 # 5 #] (N1 = 5, N1_positions = 11)A2: [# 1 # 1 # 1 # 1 #] (N2 = 4, N2_positions = 9)

Similar to the problem with a single array, we are going to find a tangent (that is, cut one on each of the two arrays), you can divide two arrays into two parts, making

"Any number contained in the two left half of the" <= "two right half of any number"

We can observe that for these two arrays (the lengths are N1 and N2, respectively):

  1. There is a total of (2n1+1) + (2n2+1) = 2N1 + 2N2 + 2 position. Therefore, after the cut, the left and right half should contain N1 + N2 positions, each knife has a position around each

  2. In the principle of having to satisfy the 1th rule, if we cut a knife in the position subscript C2 of the array A2, then the A1 shard position subscript must be C1 = N1 + n2-c2. To give an example, if C2 = 2, then there must be C1 = 4 + 5-c2 = 7.

                  A1  1 # 2 # 3 # (4/4) # 5 #] N1 = 5 (切在数字4上,所以用(4/4)表示)
      < Span class= "Hljs-number" >position index 0 1 2 3 4 5 Span class= "Hljs-number" >6 7 8 9 n_positions = one    
      < Span class= "Hljs-number" > A2 [# 1/1 # 1 # 1 #] N2 = 4 (with/in place of #)      
      < Span class= "Hljs-number" >position index 0 1 2 3 4 5 Span class= "Hljs-number" >6 7 8                    n_positions = 9  
     
  3. After the cut we will get 2 L and 2 R, respectively:

     L1 = A1[(C1-1)/2]; R1 = A1[C1/2]; L2 = A2[(C2-1)/2]; R2 = A2[C2/2];

In the example above, L1 and L2 are,

    L1 = A1[(7-1)/2] = A1[3] = 4; R1 = A1[7/2] = A1[3] = 4; L2 = A2[(2-1)/2] = A2[0] = 1; R2 = A1[2/2] = A1[1] = 1;

So now the question is, how do we know the current cut is the way we want it? A review of what we want to satisfy is that the number of all left halves is smaller than the right half. Because two arrays are ordered increment, so L1, L2 is the left half of the largest number of two, and R1, R2 is the right half of the smallest two number, so in fact, only need to meet the following conditions:

L1 <= R1 && L1 <= R2 && L2 <= R1 && L2 <= R2

Since the array is ascending and orderly,L1 <= R1 and L2 <= R2 are sure to be satisfied, we just need to make sure that:

L1 <= R2 && L2 <= R1.

Now we can finally use a simple binary search to find the right cut: (The logic here is very important, temporarily preserving the original text)

If (L1 > R2) {
It means there is too many large numbersOn theLeft half of A1,Then we must move C1 to the left (i.e. move C2 to the right );
means that there are too many large digits in the left side of the A1 to move the Shard position C1 left
}If (L2 > R1) {
Then there is too many large numbers on the left half of A2, and we must move C2 to the left .
means that there are too many large digits in the left side of the A2 to move the Shard position C2 left
}otherwise, this cut was the right one .
Otherwise it satisfies the condition that is correct for slicing, by calculating (Max (L1,L2) + min (R1,R2))/2 to obtain the median after we find the cut, the medium can is computed as (max (L1, L2) + min (R1, R2))/ 2;

Two places to note:

A. Since C1 and C2 have interdependent relationships (that is, the C1 is determined C2, and vice versa), we can move one of them first and the other move along. (There's no electricity.) Let's do that tomorrow. We can just move one of them first, then calculate the other accordingly. However, it's much more practical-to-move C2 (the one on the shorter array) first. The reason is, and the shorter array, all positions is possible cut locations for median, and on the longer array, the Positions that is too far left or right is simply impossible for a legitimate cut. For instance, [1], [2 3 4 5 6 7 8]. Clearly the cut between 2 and 3 are impossible, because the shorter array does not having that many elements to balance out t He [3 4 5 6 7 8] Part if do the cut this. Therefore, for the longer array to is used as the basis for the first cut, a range check must is performed. It would is just easier to does it on the shorter array, which requires no checks whatsoever. Also, moving only on the shorter array gives a run-time complexity of O (log (min (N1, N2))) (edited as suggested by @baselRu s)

B. The only edge case was when a cut falls on the 0th (first) or the 2Nth (last) position. For instance, if C2 = 2N2, then R2 = A2[2*N2/2] = a2[n2], which exceeds the boundary of the array. To solve the problem, we can imagine that both A1 and A2 actually has both extra elements, Int_max at A[-1] and Int_max A T A[n]. These additions don ' t change the result, and make the implementation easier:if any L falls out of the the left boundary of th e array, then L = Int_min, and if any R falls out of the right boundary, then R = Int_max.

OK, to this end, the source code is not affixed, see understand after using their familiar language to write a try Bai, really do not go to the original link to see, the great God is how to write.

Good luck!

[Leetcode] 4. Median of two 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.