题目:4. 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(m+n)
,题目保证所给的两个数组不会全部为空。
分析
- 第一种思路:这里我们使用python magic,从而快速解决这个问题,直接num1,num2合并,然后排序输出。见Python Magic Code1
- 第二种思路:题目要求时间复杂度为O(m+n),即两个数组需要一次遍历然后给出结果,那么 最直接的思路为:使用插入排序 合并两个有序数组,然后输出中间位置即可。见Code2。
- 第三种思路:使用二分搜索,时间复杂度为O(log(min(m,n)); 即使用二分法查找,而非简单的全部遍历一次。也是本题所提供的一种思路。见Code Binary Search & C++。
- 使用python复现第二种思路。见 Code & Binary Search & Python
针对第一种思路,我们先使用python简单快捷实现
Python Magic & Code1
class Solution(object):
def findMedianSortedArrays(self, num1, num2):
num1.extend(num2)
num1.sort()
return num1[len(num1)//2] if len(num1)%2==1 else (num1[len(num1)//2-1] + num1[len(num1)//2])/2.
结果:
Runtime: 88 ms, faster than 96.75% of Python3 online submissions for Median of Two Sorted Arrays.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Median of Two Sorted Arrays.
针对上面这种解法,如果我们使用C++会是怎样呢?代码见下。
C++ MergeSort & Code1
class Solution {
public:
double findMedianSortedArrays(vector<int>& num1, vector<int>& num2) {
vector<int> ans;
merge(num1.begin(), num1.end(), num2.begin(), num2.end(), back_inserter(ans));
if(ans.size()%2){
return ans[ans.size()/2];
}
return (ans[ans.size()/2-1]+ans[ans.size()/2])/2.0;
}
};
结果:
Runtime: 48 ms, faster than 44.61% of C++ online submissions for Median of Two Sorted Arrays.
Memory Usage: 22.3 MB, less than 100.00% of C+