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
1 | nums1 = [1, 3] |
Example 2
1 | nums1 = [1, 2] |
解题思路
将两个数组分别分割为左右两部分,二者左边元素数量之和应该为总数量的一半。若左边元素都小于等于右边元素,即nums1中左边最大元素小于等于nums2中右边最小元素且nums2中左边最大元素小于等于nums1中右边最小元素,则中位数能够由这四个元素产生。若不满足,需要将nums1中的分割点向左或向右移动。
复杂度分析
- 时间复杂度:$O(min(m,n))$,最坏情况下需要移动半个数组
- 空间复杂度:$O(1)$
代码
1 |
|
改进
在移动分割点时,采用二分法确定位置,使算法的时间复杂度降低到:$O(log(min(m,n)))$
1 | double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { |