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
class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int len1 = nums1.size();
int len2 = nums2.size();
if(len1>len2) return findMedianSortedArrays(nums2,nums1);
int k = (len1+len2+1)/2;
int left = 0;
int right = len1;
int mid = 0;
int m2 = 0;
while(left<right)
{
mid = left + (right-left)/2;
m2 = k - mid;
if(nums1[mid]<nums2[m2-1]) left = mid+1;
else right = mid;
}
mid = left;
m2 = k - mid;
int c1 = max(mid<=0 ? INT_MIN : nums1[mid-1] , m2<=0 ? INT_MIN :nums2[m2-1] );
if((len1+len2)%2==1) return c1;
int c2 = min(mid>=len1 ? INT_MAX : nums1[mid],m2>=len2 ? INT_MAX : nums2[m2]);
return (c1+c2)/2.0;
}
};