给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/median-of-two-sorted-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
看到这个题目第一个想法就是用直接合并两个数组然后取中位数的方法。
要注意的就是几个数组为空的情况需要考虑进去
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums;
int a = nums1.length;
int b = nums2.length;
nums = new int[m + n];
if (a== 0) {
if (b % 2 == 0) {
return (nums2[b / 2 - 1] + nums2[b / 2]) / 2.0;
} else {
return nums2[b / 2];
}
}
if (b == 0) {
if (a % 2 == 0) {
return (nums1[a / 2 - 1] + nums1[a / 2]) / 2.0;
} else {
return nums1[a / 2];
}
}//讨论当两个数组其中一个为空的情况
int count = 0;
int i = 0, j = 0;
while (count != (a + b)) {
if (i == a) {
while (j != b) {
nums[count++] = nums2[j++];
}
break;
}
if (j == b) {
while (i != a) {
nums[count++] = nums1[i++];
}
break;
}//当一组数被排列完后
if (nums1[i] < nums2[j]) {
nums[count++] = nums1[i++];
} else {
nums[count++] = nums2[j++];
}
}
if (count % 2 == 0) {
return (nums[count / 2 - 1] + nums[count / 2]) / 2.0;
} else {
return nums[count / 2];
}
}
但是这个不符合我们对复杂度的要求,所以我看了其他大佬的解答,看见一种有趣的思路就是,取中位数就是找到第k/2小的数这样子我们可以通过不断排除比k/2还小的数来达到目的。附上大佬的解法
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length;
int m = nums2.length;
int left = (n + m + 1) / 2;
int right = (n + m + 2) / 2;
return (getKth(nums1, 0, n - 1, nums2, 0, m - 1, left) + getKth(nums1, 0, n - 1, nums2, 0, m - 1, right)) * 0.5;
}//将奇数偶数情况统一起来
private int getKth(int[] nums1, int start1, int end1, int[] nums2, int start2, int end2, int k) {
int len1 = end1 - start1 + 1;
int len2 = end2 - start2 + 1;
if (len1 > len2) return getKth(nums2, start2, end2, nums1, start1, end1, k);//确保len1小于len2
if (len1 == 0) return nums2[start2 + k - 1];
if (k == 1) return Math.min(nums1[start1], nums2[start2]);
int i = start1 + Math.min(len1, k / 2) - 1;
int j = start2 + Math.min(len2, k / 2) - 1;
if (nums1[i] > nums2[j]) {
return getKth(nums1, start1, end1, nums2, j + 1, end2, k - (j - start2 + 1));
}
else {
return getKth(nums1, i + 1, end1, nums2, start2, end2, k - (i - start1 + 1));
}
}