地址:https://leetcode.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 ( l o g ( m + n ) ) O(log (m+n)) 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
理解:
寻找两个有序数组的中位数。
第一次刷hard,并不会?
Share my O(log(min(m,n)) solution with explanation
Binary Search : Median of two sorted arrays of different sizes.
设nums1
的长度为lenX
,nums2
的长度为lenY
。
中位数的性质说明,我们可以将这两个数组分别进行分割,使得左侧的元素数目和右侧相同。
对于长度为n
的数组,一共有n+1个位置可以进行分隔
两个数组合起来的长度是nums1+nums2
,其左边的元素个数应该是(lenX+lenY+1)/2
,其中加1是为了在和为奇数的情况下,让左边比右边多一个元素,方便后面的处理。
因此,记nums1
被划分为partitionX
和nums1-partitionX
两部分,因为合数组的左侧长度为(lenX+lenY+1)/2
,因此num2左侧长度partitionY=(lenX+lenY+1)/2-partitionX
。
现在的情况下,数组的长度是满足要求的,如果我们还让左侧所有的数都小于右侧所有的数,根据定义,我们的划分是中间的,因此就找到了中位数。
为了满足要求,需要:nums1[partitionX-1]<=nums2[partitionY]
且nums2[partitionY-1]<=nums1[partitionX]
- 如果满足要求,则现在的划分是合理的。
- 如果总数为偶数,则中位数为中间两个数的平均值,因此我们需要计算左边的最大和右边最小的均值。
- 如果总数为奇数,中位数为最中间的一个。因为我们划分的时候总让左侧多1,因此,返回左侧的最大值就可以了。
- 如果不满足要求,就调整划分
- 如果
nums1[partitionX-1]>nums2[partitionY]
,说明现在nums1
的划分偏右了,需要减小 - 如果
nums2[partitionY-1]>nums1[partitionX]
,说明nums1
的划分偏左了,需要增加
- 如果
在划分的过程中,我们采用二分查找来划分nums1
,以把复杂度降为
l
o
g
(
)
log()
log()。为了进一步降低复杂度,我们总在短的数组上进行划分。
如果partition=0
,说明左侧为空,我们把左边的最大元素记为INT_MIN
就可以了;partition=lenX
同理,把最右边最小元素记为INT_MAX
。
实现:
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
if (nums1.size() > nums2.size())
return findMedianSortedArrays(nums2, nums1);
int lenX = nums1.size(), lenY = nums2.size();
int l = 0;
int h = lenX;
while (l <= h) {
// the position partitionX point to is divided to the right part
int partitionX = l + (h - l) / 2;
// lenX + lenY + 1 guarantee that left is equal or more than right
int partitionY = (lenX + lenY + 1) / 2 - partitionX;
// if left part is empty, mark its biggest value as INT_MIN
int maxLeftX = partitionX == 0 ? INT_MIN : nums1[partitionX - 1];
// if left part is empty, mark its smallest value as INT_MAX
int minRightX = partitionX == lenX ? INT_MAX : nums1[partitionX];
int maxLeftY = partitionY == 0 ? INT_MIN : nums2[partitionY - 1];
int minRightY = partitionY == lenY ? INT_MAX : nums2[partitionY];
if (maxLeftX <= minRightY&&maxLeftY <= minRightX) {
if ((lenX + lenY) % 2 == 0)
return (static_cast<double>(max(maxLeftX, maxLeftY)) + min(minRightX, minRightY)) / 2;
else
return static_cast<double>(max(maxLeftX, maxLeftY));
}
else if (maxLeftX > minRightY) {
//this means left part of nums1 should shrink to left part
h = partitionX - 1;
}
else
l = partitionX + 1;
}
}
};