c++-median-of-two-sorted-arrays
题目描述
There are two sorted arrays A and B 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)).
提供两种解法:
解法1:将两个数组由小到大合并为一个,然后找出中间值即可:
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
vector<int> res;
int i=0;
int j=0;
if(m==0){
if(n%2==0)
return (double)(B[n/2]+B[n/2-1])/2;
else
return (double)(B[n/2]);
}
if(n==0){
if(m%2==0)
return (double)(A[m/2]+A[m/2-1])/2;
else
return (double)(A[m/2]);
}
while(i<m){
while(j<n){
if(A[i]>=B[j]){
res.push_back(B[j]);
j++;
}
else{
res.push_back(A[i]);
i++;
break;
}
}
if(j==n && i<m){
res.push_back(A[i]);
i++;
}
}
if(i==m && j<n){
while(j<n){
res.push_back(B[j]);
j++;
}
}
int len=res.size();
if(len%2==0){ //偶数个
return (double)(res[len/2-1]+res[len/2])/2;
}
else{
return (double)(res[len/2]);
}
}
};
解法2:其实并不需要将全部数组排序,只需要将一半的数组排序即可,因为只需要中间值,这样可节省一半时间:
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
vector<int> res;
int i=0;
int j=0;
int mid=(m+n)/2+1;
if(m==0){
if(n%2==0)
return (double)(B[n/2]+B[n/2-1])/2;
else
return (double)(B[n/2]);
}
if(n==0){
if(m%2==0)
return (double)(A[m/2]+A[m/2-1])/2;
else
return (double)(A[m/2]);
}
while(i<m && j<n){
if(A[i]>=B[j]){
res.push_back(B[j]);
j++;
}
else{
res.push_back(A[i]);
i++;
}
if(res.size()==mid)
break;
}
while(res.size()!=mid){
if(i<m){
res.push_back(A[i]);
i++;
}
if(j<n){
res.push_back(B[j]);
j++;
}
}
if((n+m)%2==0){
return (res[mid-2]+res[mid-1])/2.0;
}
else{
return (res[mid-1]);
}
}
};
posted on 2017-12-26 16:54 sichenzhao 阅读(149) 评论(0) 编辑 收藏 举报