首页 > 代码库 > Median of Two Sorted Arrays

Median of Two Sorted Arrays

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

 

 1 public class Solution { 2     public double findMedianSortedArrays(int A[], int B[]) { 3         int alen = A.length; 4         int blen = B.length; 5         if((alen + blen) % 2 == 1) return findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 1) / 2); 6         else return (double) (findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen) / 2) + findKthElement(A, B, 0, alen - 1, 0, blen - 1, (alen + blen + 2) / 2)) / 2.0; 7     } 8     private int findKthElement(int arra[], int arrb[], int ast, int and, int bst, int bnd, int num){ 9         if(ast > and) return arrb[bst + num - 1];10         if(bst > bnd) return arra[ast + num - 1];11         int amid = (ast + and) / 2;12         int bmid = (bst + bnd) / 2;13         int len = amid - ast + 1 + bmid - bst + 1;14         if(arra[amid] < arrb[bmid]){15             if(len <= num) return findKthElement(arra, arrb, amid + 1, and, bst, bnd, num - amid + ast - 1);16             else return findKthElement(arra, arrb, ast, and, bst, bmid - 1, num);17         }else{18             if(len <= num) return findKthElement(arra, arrb, ast, and, bmid + 1, bnd, num - bmid + bst - 1);19             else return findKthElement(arra, arrb, ast, amid - 1, bst, bnd, num);20         }21     }22 }