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(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 第一种思路:采用最暴力的方法,因为给的两个数组都已经排序了,也知道中位数是第几个,直接采用二分归并排序到中位数。
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
vector<int> nums3;
int i=,j=,k=;
int m =(nums1.size()+nums2.size());
while(i<nums1.size()&&j<nums2.size()) {
if(nums1[i]<nums2[j])
nums3.push_back(nums1[i++]);
else
nums3.push_back(nums2[j++]);
k++;
if(k>m/)
{
if(m%)
return nums3[k-];
else
return (nums3[k-]+nums3[k-])/2.0;
}
}
while(i<nums1.size()){
nums3.push_back(nums1[i++]);
k++;
if(k>m/)
{
if(m%)
return nums3[k-];
else
return (nums3[k-]+nums3[k-])/2.0;
}
}
while(j<nums2.size()){
nums3.push_back(nums2[j++]);
k++;
if(k>m/)
{
if(m%)
return nums3[k-];
else
return (nums3[k-]+nums3[k-])/2.0;
}
}
return ;
}
};
在leetcode中时间为48ms。