码迷,mamicode.com
首页 > 其他好文 > 详细

Median of Two Sorted Arrays

时间:2014-06-30 06:05:58      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   数组   

题目

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

方法

转换为寻找第k大的数。
参考:http://blog.csdn.net/zxzxy1988/article/details/8587244
	private int findValue(int A[], int leftA, int[] B, int leftB, int k) {
		if (A.length - leftA > B.length - leftB) {
			return findValue(B, leftB, A, leftA, k);
		} 
		if (A.length - leftA == 0) {
			return B[k - 1];
		}
		if (k == 1) {
			return Math.min(A[leftA], B[leftB]);
		}
		int a = Math.min(k / 2, A.length - leftA);
		int b = k - a;
		
		if (A[a + leftA - 1] == B[b + leftB - 1]) {
			return A[a + leftA - 1];
		} else if (A[a + leftA - 1] > B[b + leftB - 1]){
			return findValue(A, leftA, B, leftB + b, k - b);
		} else {
			return findValue(A, leftA + a, B, leftB, k - a);
		}
	}
    public double findMedianSortedArrays(int A[], int B[]) {
    	int lenA = A.length;
    	int lenB = B.length;
    	int sum = lenA + lenB;
    	if ((sum & 1) == 1) {
    		return findValue(A, 0, B, 0, sum / 2 + 1);
    	} else {
    		return (findValue(A, 0, B, 0, sum / 2) + findValue(A, 0, B, 0, (sum/2 + 1))) / 2.0;
    	}
    }


Median of Two Sorted Arrays,布布扣,bubuko.com

Median of Two Sorted Arrays

标签:java   leetcode   数组   

原文地址:http://blog.csdn.net/u010378705/article/details/35551005

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!