您的位置:首页 > 其它

lintcode, 两个排序数组的中位数

2016-11-29 19:57 435 查看
两个排序的数组A和B分别含有m和n个数,找到两个排序数组的中位数,要求时间复杂度应为O(log (m+n))。

给出数组A = [1,2,3,4,5,6] B = [2,3,4,5],中位数3.5

给出数组A = [1,2,3] B = [4,5],中位数 3

解题思路:需要满足时间复杂度为logn,结合findkth的思路,每次判断A和B在k/2位置的大小关系,然后舍弃数组中的部分数字,不断二分。找到一个具体的分析在下面的链接里

http://www.cnblogs.com/yuzhangcmu/p/4138184.html

一刷没有ac

二刷没有ac

class Solution {
/**
* @param A: An integer array.
* @param B: An integer array.
* @return: a double whose format is *.5 or *.0
*/
public double findMedianSortedArrays(int[] A, int[] B) {
if (A == null && B == null) return 0;
int len = A.length + B.length;
if (len % 2 == 0){
return (findKth(A, 0, B, 0, len/2) + findKth(A, 0, B, 0, len/2 + 1)) / 2.0;
}
return findKth(A, 0, B, 0, len/2+1);
}
public static double findKth(int[] A, int startA, int[] B, int startB, int k){
if (startA >= A.length){
return B[startB + k - 1];
}
if (startB >= B.length){
return A[startA + k - 1];
}
if (k == 1){
return Math.min(A[startA], B[startB]);
}
int keyA = startA + k / 2 - 1 < A.length ? A[startA + k / 2 - 1] : Integer.MAX_VALUE;
int keyB = startB + k / 2 - 1 < B.length ? B[startB + k / 2 - 1] : Integer.MAX_VALUE;
if (keyA < keyB){
return findKth(A, startA + k / 2, B, startB, k - k / 2);
}
return findKth(A, startA, B, startB + k / 2, k - k / 2);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode