您的位置:首页 > 其它

leetcode 4. Median of Two Sorted Arrays

2016-05-22 17:49 351 查看
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)).

求两个有序数组合并后的中位数,要求时间复杂度为O(log(m+n))

package problems.algorithms;

/**
* 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)).
* 求两个有序数组的中位数,要求O(log(m+n))
*/
public class A4MedianofTwoSortedArrays {

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int k = m + n;
if ((k & 1) == 1) {
return findKth(nums1, 0, m, nums2, 0, n, k / 2 + 1);
} else {
return (double)(findKth(nums1, 0, m, nums2, 0, n, k / 2 + 1) +
findKth(nums1, 0, m, nums2, 0, n, k / 2)) / 2;
}
}

//找到两个有序数组合并后的第k个数
public int findKth(int[] a, int aStart, int aLength, int[] b, int bStart, int bLength, int kth) {
if(aLength > bLength)
return findKth(b, bStart, bLength, a, aStart, aLength, kth);
if(aLength == 0)
return b[bStart + kth - 1];
if(kth == 1)
return Math.min(a[aStart], b[bStart]);

int pa = Math.min(kth / 2, aLength), pb = kth - pa;
if(a[aStart + pa - 1] < b[bStart + pb -1]) {
return findKth(a, aStart + pa, aLength - pa, b, bStart, bLength, kth - pa);
} else if(a[aStart + pa - 1] > b[bStart + pb -1]) {
return findKth(a, aStart, aLength, b, bStart + pb, bLength - pb, kth - pb);
} else {
return a[aStart + pa - 1];
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: