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
Solution
给两个已经排序的数组,至少有一个非空,在O(log(m + n)) 的时间里找到两个数组的中位数。在统计学上,中位数的作用是将一组数分成个数相同的两部分,并且左半部分的最大值小于等于右半部分的最大值。这就是我们进行二分查找的依据。
First, make sure num2.length > num1.length, because the calculated j value may exceed the range of second array. Using I denotes the index of min value of nums1’s right part. J denotes the index of min value of nums2’ right. While imin <= imax(= for return value, because I is confirmed). If nums1[I -1] > nums2[j], it means I is to big. Vice versa. Then according the number of sum, return leftMax or average.
Code
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length){
return findMedianSortedArrays(nums2, nums1);
}
int l1 = nums1.length, l2 = nums2.length;
int imin = 0, imax = nums1.length, halfSum = (l1 + l2 + 1) / 2;
while (imin <= imax){
int i = (imin + imax) / 2;
int j = halfSum - i;
if (i < l1 && nums2[j -1] > nums1[i]){// i is too small
imin = i + 1;
}
else if (i > 0 && nums1[i - 1] > nums2[j]){//i is too big
imax = i - 1;
}
else{
int leftMax = Integer.MIN_VALUE;
if (i == 0){
leftMax = nums2[j - 1];
}
else if (j == 0){
leftMax = nums1[i - 1];
}
else{
leftMax = Math.max(nums1[i - 1], nums2[j - 1]);
}
if ((l1 + l2) % 2 == 1){//odd sum number
return leftMax;
}
int rightMin = Integer.MAX_VALUE;
if (i == l1){
rightMin = nums2[j];
}
else if (j == l2){
rightMin = nums1[i];
}
else{
rightMin = Math.min(nums1[i], nums2[j]);
}
return (rightMin + leftMax) / 2.0;
}
}
return 0;
}
}
Time Complexity: O(log(m+n))
Space Complexity: O(1)