题目链接:https://leetcode.com/problems/median-of-two-sorted-arrays/#/description
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
解题思路:其实这道题的思路倒不难,两个排好序的数组归到一个数组中,依次选取两个数组中小的一个添加到新的数组中,主要是各种细节要考虑到,比如输入的其中一个数组为空,for循环中其中一个数组遍历结束的时候……
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
double ret = 0;
int m = nums1.size();
int n = nums2.size();
vector<int> ans(m+n);
int index0 = -1, index1 = -1;
if((m+n) % 2 == 0){
index1 = (m+n) / 2;
index0 = index1 - 1;
}
else
index0 = (m+n-1) / 2;
if(m==0){
if(index1 == -1)
return nums2[index0];
else
return static_cast<double>(nums2[index0]+nums2[index1])/2;
} else if(n==0){
if(index1 == -1)
return nums1[index0];
else
return static_cast<double>(nums1[index0]+nums1[index1])/2;
}
else {
int a = 0, b = 0;
for(int i = 0; i < m+n; ++i){
if(a < m && b < n){
if(nums1[a] < nums2[b])
ans[i] = nums1[a++];
else
ans[i] = nums2[b++];
} else {
if(a == m)
ans[i] = nums2[b++];
else
ans[i] = nums1[a++];
}
if(i==index0 && index1==-1)
return ans[i];
else {
if(i==index0)
ret = ans[i];
else if(i==index1){
return static_cast<double>(ret+ans[i])/2;
}
}
}
}
return ret;
}