Leetcode: 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)).

 

 

2017/2/5更新:如果一定要每次扔一半,使得时间复杂度为O(log(m+n))。可以在第一个数组找前k1个,第二个数组找前k2个,使得k1+k2 == k, 分情况:

1. if A[k1] < B[k2], then A[k1]及之前的、B[k2+1]及之后的都不可能成为第k个元素,所以扔掉

2. else if A[k1] > B[k2], then A[k1+1]及之后的、 B[k2]及之前的都不可能成为第k个元素。扔掉 

if (aMid < bMid) Keep [aRight + bLeft]    
else Keep [bRight + aLeft]
 1 public class Solution {
 2     public double findMedianSortedArrays(int A[], int B[]) {
 3         if((A.length+B.length)%2==1)
 4             return helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1);
 5         else
 6             return (helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2)  
 7                    +helper(A,B,0,A.length-1,0,B.length-1,(A.length+B.length)/2+1))/2.0;
 8     }
 9     
10     private int helper(int A[], int B[], int i, int i2, int j, int j2, int k)
11     {
12         int m = i2-i+1;
13         int n = j2-j+1;
14         if(m>n)
15             return helper(B,A,j,j2,i,i2,k);
16         if(m==0)
17             return B[j+k-1]; //这是相对距离,不是相对于0,而是这轮起点j,所以决定了25行27行要减posA或posB
18         if(k==1)
19             return Math.min(A[i],B[j]);
20         int posA = Math.min(k/2,m);
21         int posB = Math.min(k-posA, n);
22 
23         if(A[i+posA-1]<B[j+posB-1])
24             return helper(A,B,i+posA,i2,j,j+posB-1,k-posA);
25         else
26             return helper(A,B,i,i+posA-1,j+posB,j2,k-posB);
27     }
28 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值