LeetCode 4. Median of Two Sorted Arrays [Hard]

题目来源:

题目难度:Hard

题目

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)).

You may assume nums1 and nums2 cannot be both empty.

Example 1:

1
2
3
4
nums1 = [1, 3]
nums2 = [2]

The median is 2.0

Example 2:

1
2
3
4
nums1 = [1, 2]
nums2 = [3, 4]

The median is (2 + 3)/2 = 2.5

解答1[Java]

1
2
3
4
5
6
7
8
9
10
11
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums = new int[nums1.length + nums2.length];
System.arraycopy(nums1, 0, nums, 0, nums1.length);
System.arraycopy(nums2, 0, nums, nums1.length, nums2.length);
Arrays.sort(nums);
if ((nums.length & 1) == 0) {
return (nums[(nums.length / 2) - 1] + nums[nums.length / 2]) / 2.0;
} else {
return nums[nums.length / 2];
}
}

时空复杂度分析

时间复杂度:$O((m+n)log(m+n))$

空间复杂度:$O(m+n)$

解法2[Java]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public double findMedianSortedArrays(int[] A, int[] B) {
int m = A.length;
int n = B.length;
if (m > n) {
int[] temp = A;
A = B;
B = temp;
int tmp = m;
m = n;
n = tmp;
}
int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2;
while (iMin <= iMax) {
int i = (iMin + iMax) / 2;
int j = halfLen - i;
if (i < iMax && B[j - 1] > A[i]) {
iMin = i + 1;
} else if (i > iMin && A[i - 1] > B[j]) {
iMax = i - 1;
} else {
int maxLeft = 0;
if (i == 0) {
maxLeft = B[halfLen - 1];
} else if (j == 0) {
maxLeft = A[halfLen - 1];
} else {
maxLeft = Math.max(A[i - 1], B[j - 1]);
}
if (((m + n) & 1) == 1) {
return maxLeft;
}

int minRight;
if (i == m) {
minRight = B[j];
} else if (j == n) {
minRight = A[i];
} else {
minRight = Math.min(B[j], A[i]);
}

return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}
}

算法分析

核心思想是二分查找。

假设 A 数组是长度为 4,B 数组长度为 6,那么把 A 数组和 B 数组混合,然后重新排序,称之为数组 C。那么数组 C 的前半部分,必定由 A 中的若干个数和 B 中的若干个数组成。

时空复杂度分析

时间复杂度:$O(log(min(m,n))$

空间复杂度:$O(1)$

拓展

思考:如果是求三个有序数组的中位数呢?

参考资料

  1. 官方题解:Median of Two Sorted Arrays - LeetCode Articles