4.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 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
第一次:
52ms的代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1=nums1.size();
int len2=nums2.size();
int i=0;
vector<double> numnew(len1+len2);
for(i=0;i<len1;i++)
{
numnew[i]=nums1[i];
}
for(int j=i,k=0;j<len1+len2,k<len2;j++,k++)
{
numnew[j]=nums2[k];
}
sort(numnew.begin(),numnew.end());
if((len1+len2)%2!=0)
return numnew[(len1+len2-1)/2];
else
return (numnew[(len1+len2)/2]+numnew[(len1+len2)/2-1])/2;
}
};
重新构建一个新的vector,对它排序