class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
// Ensure nums1 is always the shorter array
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1);
}
int x = nums1.length;
int y = nums2.length;
// Binary Search on partitionX
int low = 0;
int high = x;
while (low <= high) {
// Split the two arrays into four parts st. len(leftX) + len(leftY) = len(rightX) + len(rightY)
int partitionX = low + (high - low) / 2;
int partitionY = (x + y + 1) / 2 - partitionX; // +1 to keep left one more if total is odd
// When left side is emtpy, set maxLeft to MIN_VALUE
// When right side is empty, set minRight to MAX_VALUE
int maxLeftX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
int minRightX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];
int maxLeftY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];
int minRightY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];
// Condition satisfied: all elements in left part < right part
if (maxLeftX <= minRightY && maxLeftY <= minRightX) {
if ( (x + y) % 2 == 0) // even
return (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2.0;
else // odd: left has extra
return (double) Math.max(maxLeftX, maxLeftY);
}
// maxLeftX too large, Move partitionX to left
else if (maxLeftX > minRightY) {
high = partitionX - 1;
}
// maxLeftX too small so that maxLeftY too large, move partitionX to right
else {
low = partitionX + 1;
}
}
return 0;
}
}
Complexity Analysis
Time Complexity: O(log(min(x, y))). 假设x < y, 那么我们在[0, x]的范围内进行了二分搜索,每次搜索范围会减半,因此我们总共需要log(x)次循环。每次循环仅需constant time。因此总共时间为O(log(min(x, y))).