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


解析:求两个排序数组的中位数,数组长度分别是m和n,要求时间复杂度为O(log(m+n))。刚开始思路是利用类似合并排序的思路分别遍历两个数组,但是算法复杂度为O(n)。
查看网上的解题方法,原问题其实是一个寻找第k小数的问题,中位数实际上是第(m+n)/2小的数。对于数组a和b,比较A的第k/2小的元素A[k/2-1]和B的第k/2小的元素B[k/2-1]两个元素,有三种情况可以考虑:

1. A[k/2-1]<B[k/2-1]表示A[0]到A[k/2-1]的元素都在A和B合并之后的前k小的元素中,可以把A[0]到A[k/2-1]的元素抛弃

2. A[k/2-1]>B[k/2-1]表示B[0]到B[k/2-1]的元素都在A和B合并之后的前k小的元素中,可以把B[0]到B[k/2-1]的元素抛弃

3. A[k/2-1]=B[k/2-1]表示A[k/2-1]即为第k小的元素

参考博文地址

Java AC代码:

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

	public double findK(int[] A, int aLeft, int[] B, int bLeft, int k) {
		if (A.length - aLeft < B.length - bLeft) {
			return findK(B, bLeft, A, aLeft, k);
		} else if (bLeft >= B.length) {
			return A[k - 1];
		} else if (k == 1) {
			return Math.min(A[aLeft], B[bLeft]);
		}
		int pb = Math.min(k / 2, B.length - bLeft);
		int pa = k - pb;
		if (A[aLeft + pa - 1] > B[bLeft + pb - 1]) {
			return findK(A, aLeft, B, bLeft + pb, k - pb);
		} else if (A[aLeft + pa - 1] < B[bLeft + pb - 1]) {
			return findK(A, aLeft + pa, B, bLeft, k - pa);
		} else {
			return A[pa - 1];
		}
	}
}


 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值