思路:在有序序列中找第n小和第n+1小(n,n1),当size1+size2为偶数时返回n小,否则返回(n+n1)/2,用两个指针记录遍历的两个数组的当前位置。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int s1 = nums1.size();
int s2 = nums2.size();
if(s1==0){
return s2%2==0?((double)nums2[s2/2-1]+(double)nums2[s2/2])/2:(double)nums2[s2/2];
}
else if (s2==0){
return s1%2==0?((double)nums1[s1/2-1]+(double)nums1[s1/2])/2:(double)nums1[s1/2];
}
int pos1 = 0;
int pos2 = 0;
int siz = nums1.size() + nums2.size();//奇数3 找第2大 siz/2+1,偶数4
int index = 0;
int n;//寻找第n小和第n+1小
int n1;
int flag = 0;
while(index<siz/2){
if(nums1[pos1]>nums2[pos2]){
n=nums2[pos2];
pos2++;
}
else{
n=nums1[pos1];
pos1++;
}
index++;
if(pos1==nums1.size()){
flag = 1;
break;
}
if(pos2==nums2.size()){
flag = 2;
break;
}
}
if(flag==1){
if(index!=siz/2)
n=nums2[pos2+siz/2-index-1];
n1=nums2[pos2+siz/2-index];
}
else if(flag==2){
if(index!=siz/2)
n=nums1[pos1+siz/2-index-1];
n1=nums1[pos1+siz/2-index];
}
else{
if(nums1[pos1]>nums2[pos2]){
n1=nums2[pos2];
pos2++;
}
else{
n1=nums1[pos1];
pos1++;
}
}
if(siz%2==0){
return ((double)n+(double)n1)/2;
}
else
return (double)n1;
}
};
这题还可以用二分查找来做