您的位置:首页 > 其它

Median of Two Sorted Arrays -- LeetCode

2015-04-02 22:10 197 查看
Problem:

 http://oj.leetcode.com/problems/median-of-two-sorted-arrays/ 

Solution:

A easy idea to come up with is that using the what we use in Merge Sorted Array.  Combine to sorted Array together,
when we got to the (m+n)/2 number, we simply return it. So we can get the median of these two sorted array.

The code is simple won't list here.

But how can we improve our algorithm? The idea comes from order statistics. 

Every time, we compare two arrays, we compare the K/2 number in each array. If A[k/2] == B[k/2], that's the number we need. If A[k/2] > B[k/2], then the first K/2 numbers in array B is not the number we are looking for. Correspondingly we can get rid of
the first K/2 number in array A.

In the problem, k=(m+n)/2. so the complexity is O(log(m+n)).

Code:

public class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
if((A.length+B.length)%2 == 1){
return helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2 +1);
}else{
return (helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2)+helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1))/2.0;
}
}

private int helper(int A[],int B[],int astart,int aend,int bstart,int bend,int k){
int m = aend-astart+1;
int n = bend-bstart+1;
if(m>n){
return helper(B,A,bstart,bend,astart,aend,k);
}
if(m==0){
return B[bstart+k-1];
}
if(k==1){
return Math.min(A[astart],B[bstart]);
}
int posA = Math.min(k/2,m);
int posB = k - posA;
if(A[astart+posA-1] == B[bstart+posB-1]){
return A[astart+posA-1];
}else if(A[astart+posA-1] < B[bstart + posB-1]){
return helper(A,B,astart+posA,aend,bstart,bend,k-posA);
}else{
return helper(A,B,astart,aend,bstart+posB,bend,k-posB);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: