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)).
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
AC代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int i=0, j=0; // 这两个变量用于作为index指示在数组中的位置
int x=0, y=0; // x, y用于指示两个数组中遍历到的的当前值
int pre_val=0, cur_val=0; // 这两个变量用于指示当前值和前一个值
int count=1; // count用于指示当前总共遍历的数的个数
int sum_size = nums1.size() + nums2.size();
int target = sum_size/2 + 1;
bool even = (sum_size%2 == 1) ? true:false;
while(1) {
// 有可能存在数组越界的情况,因此这里给越界的情况加一个临时值,便于后面的判断
if(i<nums1.size()) {
x = nums1[i];
} else {
x = INT_MAX - 1;
}
if(j<nums2.size()) {
y = nums2[j];
} else {
y = INT_MAX - 1;
}
// 如果数组中的值超过了INT_MAX, 直接返回0
if(x >= INT_MAX || y >= INT_MAX) return 0;
// 取当前最小的值作为cul_val,相当于是一个排序
if(x < y) {
cur_val = x;
++i;
} else {
cur_val = y;
++j;
}
// count == target 说明已经到了中位数的位置,接下来要来判定奇偶性
if(count == target) {
if(even) {
return cur_val;
} else {
return double((cur_val + pre_val)/2.0);
}
}
// 设置pre_val的初衷就是解决偶数的情况
pre_val = cur_val;
++count;
}
}
};
测试代码
int main() {
Solution s;
vector<int> nums1{1, 3};
vector<int> nums2{2};
cout << "Median of nums1 and nums2 is " << s.findMedianSortedArrays(nums1, nums2)<<endl;
vector<int> nums3{1, 2};
vector<int> nums4{3, 4};
cout << "Median of nums3 and nums4 is " << s.findMedianSortedArrays(nums3, nums4)<<endl;
}
总结
这题的难度属于Hard,上述的解法的核心思想是同时遍历两个数组,根据当前的最小值决定遍历的走向。注释比较详细。