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
首先保证两个vector都不为空,其次将两个vector里面较小的一半加入到一个新的vector中,判断两个vector容器的size和是否为偶数,若是则对末尾两个求平均数,否则直接返回末尾数。
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int nums_length = nums1.size() + nums2.size();
if (nums_length==0)return 0;
if (nums1.size() == 0) {
nums1.push_back(nums2.back());
nums2.pop_back();
}
if (nums2.size() == 0) {
nums2.push_back(nums1.back());
nums1.pop_back();
}
vector<int> nums;
int i = 0, j = 0;
nums1.push_back(INT_MAX);
nums2.push_back(INT_MAX);
while ((i + j) <= (nums_length >> 1)) {
if (nums1[i] > nums2[j]) {
nums.insert(nums.end(),nums2[j]);
j++;
}else{
nums.insert(nums.end(), nums1[i]);
i++;
}
}
if ((nums_length & 1) == 0) {
int last = nums.back();
nums.pop_back();
last += nums.back();
return 1.0*last / 2;
}
return nums.back();
}