leetcode 求两个排序数组的中位数


好复杂的二分思路。。。。

public static double findMedianSortedArrays(int[] A, int[] B) {
		if (A == null && B == null)
			return -1;
//		if (A == null || A.length == 0)  //不可,另一个 可能是偶数个
//			return B[B.length / 2];
//		if (B == null || B.length == 0)
//			return A[A.length / 2];

		int count = A.length + B.length;
		if ((count & 1) == 1)
			return getK(A, 0, A.length - 1, B, 0, B.length - 1, count / 2 + 1);
		else {
			double sum = getK(A, 0, A.length - 1, B, 0, B.length - 1,
					count / 2 + 1)
					+ getK(A, 0, A.length - 1, B, 0, B.length - 1, count / 2);
			return sum / 2;
		}
	}

	//这个函数的作用是找到两个数组中的第k个数
	public static int getK(int A[], int aBeg, int aEnd, int B[], int bBeg,
			int bEnd, int k) {
		System.out.println(aBeg+" "+aEnd+" "+bBeg+" "+bEnd+" "+k);
		if(aBeg>aEnd){  //A已经不用考虑了,直接在B中就可以求出第K个数
			return B[bBeg+k-1];
		}
		if(bBeg>bEnd){
			return A[aBeg+k-1];
		}
		//k==1的时候,表示当前所有数据里面,最小的那个数据 就是第k个值啦,所以以下:
		if(k==1) return Math.min(A[aBeg], B[bBeg]);  
		
		
		int aMid = (aBeg + aEnd) / 2;
		int bMid = (bBeg + bEnd) / 2;

		int count = aMid - aBeg + bMid - bBeg + 2;
//		if (count == k) // 注意k==count时  不代表 最大值就是那个k值  例子 {1 2 }{1 1}
//			return Math.max(A[aMid], B[bMid]);
		 if (count > k) {
			if (A[aMid] > B[bMid]) {
				return getK(A, aBeg, aMid-1 , B, bBeg, bEnd, k); // 忘记return了。。
			} else {
				return getK(A, aBeg, aEnd, B, bBeg, bMid-1 , k);
			}
		} else {
			if (A[aMid] < B[bMid]) {
				return getK(A, aMid+1 , aEnd, B, bBeg, bEnd, k - (aMid-aBeg+1) );  //这里的+1不可以省略,否则会死循环!!!
			} else {
				return getK(A, aBeg, aEnd, B, bMid+1 , bEnd, k - (bMid-bBeg+1) );
			}
		}
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值