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)).
You may assume nums1 and nums2 cannot be both empty.
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
解题思路
因为两个数组已经排好序,那么只要在两个数组中从左往右,从小到大依次遍历总共 [ size / 2 ] 个元素即可找到目标解
注:此方法非最佳解法,最佳解法仍在学习中
C++代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int size = nums1.size() + nums2.size();
int i = 0, j = 0;
int count = 0;
int prev = 0, next = 0;
while(count <= size / 2) {
if(i < nums1.size() && j < nums2.size()) {
if(nums1[i] < nums2[j]){
prev = next;
next = nums1[i];
i++;
}
else {
prev = next;
next = nums2[j];
j++;
}
}
else {
if(j < nums2.size()) {
prev = next;
next = nums2[j];
j++;
}
else {
prev = next;
next = nums1[i];
i++;
}
}
count++;
}
return size%2? next : (next+prev)/2.0f;
}
};