4. Median of Two Sorted Arrays
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) {
//the length effects the logic. It's a good method
if(nums1.capacity() > nums2.capacity()) {
return findMedianSortedArrays(nums2, nums1);
}
int x = nums1.capacity();
int y = nums2.capacity();
int low = 0;
int high = x;
while(low<=high) {
int partitionX = (low + high) / 2;
int partitionY = (x + y) / 2 - partitionX;
//Solve the problem of array left and right overflow
int xMaxLeft = (partitionX == 0) ? INT_MIN : nums1[partitionX - 1];
int xMInRight = (partitionX == x) ? INT_MAX : nums1[partitionX];
int yMaxLeft = (partitionY == 0) ? INT_MIN : nums2[partitionY - 1];
int yMinRight = (partitionY == y) ? INT_MAX : nums2[partitionY];
if(xMaxLeft<=yMinRight && yMaxLeft<=xMInRight) {
if((x+y)%2 == 0) {
//When the denominator is an integer, the result must be an integer.
return ((double)(max(xMaxLeft, yMaxLeft) + min(xMInRight, yMinRight))) / 2;
}
else {
return (double)min(xMInRight, yMinRight);
}
} //binary search
else if(xMaxLeft > yMinRight) {
high = partitionX - 1;
}
else {
low = partitionX + 1;
}
}
return 0;
}
};