首页 > 其他 > 详细

Median of Two Sorted Arrays

时间:2015-05-18 02:04:21      阅读:252      评论:0      收藏:0      [点我收藏+]

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

?

public class Solution {
	public static void main(String[] args) {
		int a[] = {1};
		int b[] = {};
		findMedianSortedArrays(a, b);
	}
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int mid = (len1+len2)/2;
        if ((len1+len2)%2 == 0) {
        	return (findKth(nums1, nums2, mid)+findKth(nums1, nums2, mid+1))/2.0;
        } else {
        	return findKth(nums1, nums2, mid+1);
        }
    }

	public static int findKth(int A[], int B[], int k) {  
		int lenA = A.length;
		int lenB = B.length;
		if (lenA > lenB) {
			return findKth(B, A, k);
		}
		if (lenA == 0) {
			return B[k-1];
		}
		if (k == 1) {
			return Math.min(A[0], B[0]);
		}
		int pa = Math.min(k/2, lenA);
		int pb = k-pa;
		if (A[pa-1] < B[pb-1]) {
			return findKth(Arrays.copyOfRange(A, pa, lenA), B, k-pa);
		} else {
			return findKth(A, Arrays.copyOfRange(B, pb, lenB), k-pb);
		}		
	}  
}

?

Median of Two Sorted Arrays

原文:http://hcx2013.iteye.com/blog/2211973

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!