* * 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)).

 Public classSolution { Public DoubleFindmediansortedarrays (intA[],intb[]) {        intLen = A.length +b.length; if(len% 2 = = 1) {            returnFindkth (A, 0, B, 0, LEN/2 + 1); }        return(findkth (A,0, B, 0, LEN/2) + findkth (A, 0, B, 0, LEN/2 + 1)        ) /2.0; }    //find kth number of sorted array     Public Static intFindkth (int[] A,intA_start,int[] B,intB_start,intk) {                if(A_start >=a.length) {returnB[b_start + k-1]; }        if(B_start >=b.length) {returnA[a_start + k-1]; }        if(k = = 1) {            returnmath.min (A[a_start], B[b_start]); }                intA_key = A_start + K/2-1 <A.length? A[a_start + K/2-1]: integer.max_value; intB_key = B_start + K/2-1 <B.length? B[b_start + K/2-1]: Integer.max_value;
/* First assume that the number of elements of arrays A and b is greater than K/2, we compare a[k/2-1] and b[k/2-1] Two elements, these two elements represent the first K/2 small element of a and the K/2 small element of B. These two elements compare a total of three cases:>, < and =. If a[k/2-1]<b[k/2-1], this means that the elements of a[0] to a[k/2-1] are in the first K-small element after the merging of a and B. In other words, a[k/2-1] cannot be larger than the K-decimal value after the two array is merged, so we can discard it. */

if(A_key <B_key) { returnFindkth (A, A_start + K/2, B, B_start, K-k/2); } Else { returnFindkth (A, A_start, B, B_start + K/2, K-k/2); } }}

Reference

http://blog.csdn.net/yutianzuijin/article/details/11499917

* * 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.