【題目】**4. 尋找兩個正序數組的中位數
給定兩個大小爲 m 和 n 的正序(從小到大)數組 nums1 和 nums2。
請你找出這兩個正序數組的中位數,並且要求算法的時間複雜度爲 O(log(m + n))。
你可以假設 nums1 和 nums2 不會同時爲空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
則中位數是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
則中位數是 (2 + 3)/2 = 2.5
【解題思路1】二分查找
充分利用數組有序的條件
只需要在較短的數組上確定分割線的位置使用二分查找
即這條分割線,要保證數組1的線左邊最大值<=數組2右邊元素的最小值,數組2左邊元素的最大值<=數組1右邊元素的最小值,保證交叉<=,這樣就和只有一個有序數組的中位數情況統一了起來,這樣分界線左邊的兩個數中的較大者是其中一箇中位數,分界線右邊的兩個數的較小者是另一箇中位數
中位數分割線劃分條件:
1. 元素個數兩邊基本相同(最多差1)
因爲存在以上關係,所以不需要確定兩個數組的分割線,只要確定其中一個數組的分割線就可以確定另一個數組的分割線
2. 保證線左邊<=右邊,切要保證交叉<=成立
保證交叉部分也滿足<=條件
如下圖就是一個不符合條件的分割線,所以要在往第一個數組右邊尋找
爲了保證訪問下標不越界,就特殊情況討論,應該在較短數組上確定分割線的位置
分割線一共會出現下面四種特殊情況
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
int[] temp = nums1;
nums1 = nums2;
nums2 = temp;
}
int m = nums1.length;
int n = nums2.length;
// 分割線左邊的所有元素需要滿足的個數 m + (n - m + 1) / 2;
int totalLeft = (m + n + 1) / 2;
// 在 nums1 的區間 [0, m] 裏查找恰當的分割線,
// 使得 nums1[i - 1] <= nums2[j] && nums2[j - 1] <= nums1[i]
int left = 0;
int right = m;
while (left < right) {
int i = left + (right - left + 1) / 2;
int j = totalLeft - i;
if (nums1[i - 1] > nums2[j]) {
// 下一輪搜索的區間 [left, i - 1]
right = i - 1;
} else {
// 下一輪搜索的區間 [i, right]
left = i;
}
}
int i = left;
int j = totalLeft - i;
int nums1LeftMax = i == 0 ? Integer.MIN_VALUE : nums1[i - 1];
int nums1RightMin = i == m ? Integer.MAX_VALUE : nums1[i];
int nums2LeftMax = j == 0 ? Integer.MIN_VALUE : nums2[j - 1];
int nums2RightMin = j == n ? Integer.MAX_VALUE : nums2[j];
if (((m + n) % 2) == 1) {
return Math.max(nums1LeftMax, nums2LeftMax);
} else {
return (double) ((Math.max(nums1LeftMax, nums2LeftMax) + Math.min(nums1RightMin, nums2RightMin))) / 2;
}
}
}
【解題思路2】暴力法
將兩個數組合併成一個有序數組
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums;
int m = nums1.length;
int n = nums2.length;
nums = new int[m + n];
if (m == 0) {
if (n % 2 == 0) {
return (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
} else {
return nums2[n / 2];
}
}
if (n == 0) {
if (m % 2 == 0) {
return (nums1[m / 2 - 1] + nums1[m / 2]) / 2.0;
} else {
return nums1[m / 2];
}
}
int count = 0;
int i = 0, j = 0;
while (count != (m + n)) {
if (i == m) {
while (j != n) {
nums[count++] = nums2[j++];
}
break;
}
if (j == n) {
while (i != m) {
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];
}
}