一、问题描述
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
二、思路
由于本题意在求解两个有序数组的中点,而且要求时间复杂度为O(NlogN),所以自然就想到了二分法。
由于数组存在空或者指针越界的危险,所以我们在两个数组的末尾添加一个大整数。
nums1.insert(nums1.end(), INT_MAX);
nums2.insert(nums2.end(), INT_MAX);
在中间部分我们的循环主题主要是保证我们循环停止在两个数组长度和的中间部分,即(len1 + len2)/ 2。通过两个指针start1和start2来完成移动寻找。
最后我们对数组1和2的长度之和分奇偶讨论。
三、代码
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
if(len1 + len2 == 0) return 0;
nums1.insert(nums1.end(), INT_MAX);
nums2.insert(nums2.end(), INT_MAX);
int start1 = 0, start2 = 0;
int new_mid,old_mid;
for(int i = 0; i <= (len1 + len2) / 2; ++i){
old_mid = new_mid;
if(nums1[start1] > nums2[start2]) new_mid = nums2[start2++];
else new_mid = nums1[start1++];
}
if((len1 + len2) % 2 == 1) return new_mid;
else return ((double)new_mid + (double)old_mid) / 2;
}
};