Google/LintCode:H-Median of two Sorted Array

49 篇文章 0 订阅
9 篇文章 0 订阅

题目


LintCode:Link


There are two sorted arrays A and B of size m and nrespectively. Find the median of the two sorted arrays.

Example

Given A=[1,2,3,4,5,6] and B=[2,3,4,5], the median is 3.5.

Given A=[1,2,3] and B=[4,5], the median is 3.

Challenge 

The overall run time complexity should be O(log (m+n)).


分析


(1)每次至多可以确定 k/2 个元素不会是第 K 个元素

(2)TC = lgk,k 初始为 lg(m+n)


代码


public class Solution {
    /*
     * @param A: An integer array
     * @param B: An integer array
     * @return: a double whose format is *.5 or *.0
     */
    public double findMedianSortedArrays(int[] A, int[] B) {
        int an = A.length;
        int bn = B.length;
        int n = an+bn;
        
        if(n%2==0){//全数组和为偶数
            return (findKth(A,B,n/2)+findKth(A,B,n/2+1))/2.0;
        }else{
            return findKth(A,B,n/2+1);
        }
        
    }
    
    public int findKth(int[] A, int[] B, int k){
        int an = A.length;
        int bn = B.length;
        
        if(an>bn) return findKth(B,A,k);//总是使得第一个参数数组小于第二个
        if(an==0) return B[k-1];//A中的已经被排除干净了,直接取B中剩下的位数
        if(k==1) return Math.min(A[0], B[0]);//取两者中最小的,就是目标K
        
        int aIndex = Math.min(an, k/2);
        int bIndex = Math.min(bn, k/2);
        if(A[aIndex-1] > B[bIndex-1]){//可以确定,B中bIndex个不是第k元素
            return findKth(A, Arrays.copyOfRange(B, bIndex, bn), k-bIndex);
        }else{
            return findKth(Arrays.copyOfRange(A, bIndex, an), B, k-aIndex);
        }
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值