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)).
Example:
nums1 = [1, 3]
nums2 = [2]The median is 2.0
Example:
nums1 = [1, 2]
nums2 = [3, 4]The median is (2 + 3)/2 = 2.5
算法思路
主要是使用了分治的思想,想法和上一道题目Reverse Pairs 差不多。
1. 题目要我求两个已经排列好的序列A与B的中位数,两个序列的长度分别是m与n,既求两个序列中第
k=(m+n)2
个数。
2. 我们假设p和q分别是A和B的中位数(这个很容易求),然后比较p和q的大小,若p < q,说明A中P之前的数字都不是两个序列的中位数。我们就可以A面半部分的数字“抛弃”掉。现在的问题就变成了求剩下的数字中第
k−p
个数字了。
3. 我们通过这样每次都扔掉其中一个序列的一半的数字,最后就可以很快得求得问题的解。
4. 我们要注意几个边界问题。(1)如果A或者B为空,只需返回
A[k−1]
或者
B[k−1]
。(2)如果k为1,则返回
A[0]
与
B[0]
中比较小的那个数。(3)如果
A[k/2−1]=B[k/2−1]
,则随便返回其中一个。
算法代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
int i = 0;
int j = 0;
int b = (len1 + len2)/2 - (len2 + len1 + 1)%2;
int a = 0;
if(len1 != 0 && len2 !=0){
while(a != b){
if(nums1[i] <= nums2[j]){
if(i + 1 < len1)
i++,a++;
else{
break;
}
}
else if(nums1[i] > nums2[j]){
if(j + 1 < len2)
j++,a++;
else{
break;
}
}
}
if(a != b){
a = a + 1;
if(i + 1 < len1){
if((len2 + len1)%2 == 1){
return (double)nums1[i + b - a];
}
else
return ((double)nums1[i + b - a] + (double)nums1[i + b - a + 1])/2;
}
else{
if((len2 + len1)%2 == 1){
return (double)nums2[j + b - a];
}
else{
return ((double)nums2[j + b - a] + (double)nums2[j + b - a + 1])/2;
}
}
}
else{
if((len2 + len1)%2 == 1){
return (double)nums1[i] < (double)nums2[j]?(double)nums1[i]:(double)nums2[j];
}
else{
double tmp = ((double)nums1[i] + (double)nums2[j])/2;
double tmp1,tmp2;
if(i + 1 < len1){
double tmp11 = ((double)nums1[i] + (double)nums1[i+1])/2;
double tmp12 = ((double)nums1[i + 1] + (double)nums2[j])/2;
tmp1 = tmp11 < tmp12 ? tmp11:tmp12;
}
else
tmp1 = tmp;
if(j + 1 < len2){
double tmp21 = ((double)nums2[j + 1] + (double)nums2[j])/2;
double tmp22 = ((double)nums1[i] + (double)nums2[j+1])/2;
tmp2 = tmp21 < tmp22 ? tmp21:tmp22;
}
else
tmp2 = tmp;
tmp1 = tmp1 < tmp2 ? tmp1:tmp2;
tmp = tmp < tmp1?tmp:tmp1;
return tmp;
}
}
}
else if(len1 == 0){
if(len2%2 == 1){
return (double)nums2[len2/2];
}
else
return ((double)nums2[len2/2] + (double)nums2[len2/2 - 1])/2;
}
else{
if(len1%2 == 1){
return (double)nums1[len1/2];
}
else
return ((double)nums1[len1/2] + (double)nums1[len1/2 - 1])/2;
}
}
};