【leetcode with java】4 Median of Two Sorted Arrays

<pre name="code" class="plain"><pre name="code" class="java"><pre name="code" class="plain"><pre name="code" class="plain">There are two sorted arrays nums1 and nums2 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)).

Tags: Divide and Conquer, Array Binary Search


 
【分析】由于题目明确说明两个数组都是排好序的,首先会想到二分搜索,而这里恰好就用到了。
	
【上码】
 
public class Solution1 {
	
	/*
	 * java中的对象作为函数参数时是引用传递,非值传递
	 */
	public double findMedianSortedArrays(int A[], int B[]) {
		// double median;

		int len = A.length + B.length;
		if (len % 2 == 0) {
			return (findKthMIn(A, 0, A.length-1, B, 0, B.length-1, len / 2) + findKthMIn(
					A, 0, A.length-1, B, 0, B.length-1, len / 2 + 1)) / 2;
		} else {
			return findKthMIn(A, 0, A.length-1, B, 0, B.length-1, len / 2 + 1);
		}

		// return median;
	}

	public double findKthMIn(int[] A, int aL, int aR, int[] B, int bL, int bR,
			int k) {

		if ((aR - aL) > (bR - bL)) {
			//使A为较短数组
			return findKthMIn(B, bL, bR, A, aL, aR, k);
		}
		if (aR - aL < 0) {
			return B[k - 1];
		}
		if (k<=1) {
			return Math.min(A[aL], B[bL]);
		}
		
		int pa = Math.min(aR-aL+1, k/2);
		int pb = k - pa;
		
		if (A[aL+pa-1] < B[bL+pb-1]) {
			return findKthMIn(A, aL+pa, aR, B, bL, bR, k-pa);
		}
		else if(A[aL+pa-1] > B[bL+pb-1]){
			return findKthMIn(A, aL, aR, B, bL+pb, bR, k-pb);
		}
		else {
			return A[aL+pa-1];
		}
	}
}
 
 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值