Median of Two Sorted Arrays (Java)

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

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

Source

public class Solution {
    public double findMedianSortedArrays(int A[], int B[]){
    	if((A.length + B.length) % 2 != 0)
    		return (double)find(A, 0, A.length - 1, B, 0, B.length - 1, (A.length + B.length) / 2 + 1);
    	else{
    		double x = find(A, 0, A.length - 1, B, 0, B.length - 1, (A.length + B.length) / 2);
    		double y = find(A, 0, A.length - 1, B, 0, B.length - 1, (A.length + B.length) / 2 + 1);
    		return (double)(x + y) / 2;
    		}
    }
    public int find(int[] A, int start1, int end1, int[] B, int start2, int end2, int k){
    	int len1 = end1 - start1 + 1;
    	int len2 = end2 - start2 + 1;
    	
    	if(len1 > len2){
    		return find(B, start2, end2, A, start1, end1, k);
    	}
    	
    	if(len1 == 0) return B[k - 1];
    	if(k == 1) return Math.min(A[start1], B[start2]);
    	
    	int a = Math.min(k / 2, len1); //***
    	int b = k - a;
    	if(A[start1 + a - 1] < B[start2 + b - 1])
    		return find(A, start1 + a, end1, B, start2, end2, k - a);
    	else if(A[start1 + a - 1] > B[start2 + b - 1])
    		return find(A, start1, end1, B, start2 + b, end2, k - b);
    	else return A[start1 + a - 1];
    }
    
}


Test

   public static void main(String[] args){
    	int[] A = {1, 2, 3};
    	int[] B = {4, 5, 6};
    	System.out.println(new Solution().findMedianSortedArrays(A, B));
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值