【链接】https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
题目:
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:
nums1 = [1, 3] nums2 = [2] The median is 2.0
Example 2:
nums1 = [1, 2] nums2 = [3, 4] The median is (2 + 3)/2 = 2.5
思路:
一般如果题目要求时间复杂度在O(log(n)),大部分都是可以使用二分的思想来进行求解。
- 简单说来
本题是两个数组,也是一样的,我们先求出两个数组长度之和。如果为奇数,就找中间的那个数,也就是 (长度之和 1)/2 。如果为偶数,那就找 长度之和/2。此时,问题其实已经转化为“找到两个数组中第k小的元素”。找到了第k位之后,第k+1位我们已经知道了,然后第k位和第k+1位的和,除以2就是我们要找的中位数。
- 其他方案比较
-
这⼀题最容易想到的办法是把两个数组合并,然后取出中位数。但是合并有序数组的操作是O(max(n,m)) 的,不符合题意。看到题⽬给的 log 的时间复杂度,很容易联想到⼆分搜索。
-
由于要找到最终合并以后数组的中位数,两个数组的总⼤⼩也知道,所以中间这个位置也是知道的。只需要⼆分搜索⼀个数组中切分的位置,另⼀个数组中切分的位置也能得到。为了使得时间复杂度最⼩,所以⼆分搜索两个数组中⻓度较⼩的那个数组。
代码:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int size1 = nums1.size();
int size2 = nums2.size();
int total = size1+size2;
int left = (total + 1)/2;
int right = (total + 2)/2;
return (findK(nums1,0,nums2,0,left) + findK(nums1,0,nums2,0,right))/2.0;
}
int findK(vector<int>& nums1,int i, vector<int>& nums2,int j, int k){
if(i >= nums1.size())return nums2[j + k - 1];
if(j >= nums2.size())return nums1[i + k - 1];
if(k == 1)return std::min(nums1[i],nums2[j]);
//计算出每次要比较的两个数的值,来决定 "删除"" 哪边的元素
int mid1 = (i + k/2 -1)<nums1.size()?nums1[i + k/2 -1]:INT_MAX;
int mid2 = (j + k/2 -1)<nums2.size()?nums2[j + k/2 -1]:INT_MAX;
//二分趋近
if(mid1 < mid2){
return findK(nums1,i+k/2,nums2,j,k-k/2);
}
return findK(nums1,i,nums2,j+k/2,k-k/2);
}
};
参考:
【寻找两个正序数组的中位数(292)】