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 len1 = A.length;
 4         int len2 = B.length;
 5         int total = len1+len2;
 6         if(total%2==0){
 7             return (helper(A,0,len1,B,0,len2,total/2)+helper(A,0,len1,B,0,len2,total/2+1))/2;
 8         }
 9         else{
10             return helper(A,0,len1,B,0,len2,total/2+1);
11         }
12     }
13     
14     public double helper(int A[],int indexA,int m,int B[],int indexB,int n,int k){
15         if(m>n) return helper(B,indexB,n,A,indexA,m,k);
16         if(m==0) return B[indexB+k-1]/1.0;
17         if(k==1) return Math.min(A[indexA],B[indexB])/1.0;
18         int pa = Math.min(m,k/2);
19         int pb = k-pa;
20         if(A[indexA+pa-1]<B[indexB+pb-1]){
21             indexA += pa;
22             return helper(A,indexA,m-pa,B,indexB,n,k-pa);
23         }
24         else if(A[indexA+pa-1]>B[indexB+pb-1]){
25             indexB += pb;
26             return helper(A,indexA,m,B,indexB,n-pb,k-pb);
27         }
28         else{
29             return A[indexA+pa-1];
30         }
31     }
32 }
View Code

 

posted @ 2014-02-06 04:52  krunning  阅读(261)  评论(0编辑  收藏  举报