[LeetCode] Median of Two Sorted Arrays

Source: Internet
Author: User

[Cpp]
Class Solution {
// More detail refer to: http://fisherlei.blogspot.com/2012/12/leetcode-median-of-two-sorted-arrays.html
// Using the method of getting the kth number in the two sorted array to solve the median problem
// Divide-and-conquer
// Very clean and concise
Public:
Double findMedianSortedArrays (int A [], int m, int B [], int n ){
If (n + m) % 2 = 0)
{
Return (GetMedian (A, m, B, n, (m + n)/2) + GetMedian (A, m, B, n, (m + n) /2 + 1)/2.0;
}
Else
Return GetMedian (A, m, B, n, (m + n)/2 + 1 );
}
Int GetMedian (int a [], int n, int B [], int m, int k) // get the kth number in the two sorted array
{
// Assert (a & B );
If (n <= 0) return B [k-1];
If (m <= 0) return a [k-1];
If (k <= 1) return min (a [0], B [0]);
// A: section1 section2
// B: section3 section4
If (B [m/2]> = a [n/2])
{
If (n/2 + 1 + m/2)> = k)
Return GetMedian (a, n, B, m/2, k); // abort section 4
Else
Return GetMedian (a + n/2 + 1, n-(n/2 + 1), B, m, k-(n/2 + 1 )); // abort section 1
}
Else
{
If (m/2 + 1 + n/2)> = k)
Return GetMedian (a, n/2, B, m, k); // abort section 2
Else
Return GetMedian (a, n, B + m/2 + 1, m-(m/2 + 1), k-(m/2 + 1 )); // abort section 3
}
}
};

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.