您的位置:首页 > 产品设计 > UI/UE

Leetcode#4||Median of Two Sorted Arrays

2015-08-11 10:44 351 查看
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;

if ((len1 + len2) % 2 == 0) {
return (findKthElement((len1 + len2) / 2 - 1, nums1, 0, len1 - 1, nums2, 0, len2 - 1) +
findKthElement((len1 + len2) / 2, nums1, 0, len1 - 1, nums2, 0, len2 - 1)) * 0.5;
} else {
return (double) findKthElement((len1 + len2) / 2, nums1, 0, len1 - 1, nums2, 0, len2 - 1);
}
}

private int findKthElement(int loc, int[] A, int aStart, int aEnd,
int[] B, int bStart, int bEnd) {
int aLen = aEnd - aStart + 1;
int bLen = bEnd - bStart + 1;

//cornor case.
if (aLen == 0) {
return B[bStart + loc];
}
if (bLen == 0) {
return A[aStart + loc];
}
if (loc == 0) {
return Math.min(A[aStart], B[bStart]);
}

int aLoc = aLen * loc / (aLen + bLen) + aStart;
//int bLoc = bLen * loc / (aLen + bLen) + bStart;
int bLoc = loc - aLoc - 1 + aStart + bStart;

if (A[aLoc] > B[bLoc]) {
loc = loc - (bLoc - bStart + 1);
bStart = bLoc + 1;
aEnd = aLoc;
} else {
loc = loc - (aLoc - aStart + 1);
aStart = aLoc + 1;
bEnd = bLoc;
}

return findKthElement(loc, A, aStart, aEnd, B, bStart, bEnd);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息