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) {
// write your code here
int lenA = A.length;
int lenB = B.length;
int totalLen = lenA + lenB;
if (totalLen % 2 == 0) {
int sum = findKth(A, 0, B, 0, totalLen / 2) + findKth(A, 0, B, 0, 1 + totalLen / 2);
return sum / 2.0;
} else {
return findKth(A, 0, B, 0, 1 + totalLen / 2);
}
}
private int 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 a = ((startA + k / 2) > A.length) ? Integer.MAX_VALUE : A[startA + k / 2 - 1];
int b = ((startB + k / 2) > B.length) ? Integer.MAX_VALUE : B[startB + k / 2 - 1];
if (a == b) {
return a;
} else if (a > b) {
return findKth(A, startA, B, startB + k / 2, k - k / 2);
} else {
return findKth(A, startA + k / 2, B, startB, k - k / 2);
}
}
}
65.Median of two Sorted Arrays
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 重刷leetcode,刷到此题。描述: There are two sorted arrays nums1 and...
- 原题链接 描述: There are two sorted arrays nums1 and nums2 of s...
- Median of Two Sorted Arrays 这是一个leetcode上的算法题目,标记为hard。具体...
- There are two sorted arrays nums1 and nums2 of size m...
- Question Description My Code Test Result Solution Put num...