# 4. 寻找两个正序数组的中位数 Median of Two Sorted Arrays

Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return the median of the two sorted arrays.

The overall run time complexity should be `O(log (m+n))`.

Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.

Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.

```     public double findMedianSortedArrays(int[] nums1, int[] nums2){
int length1 = nums1.length;
int length2 = nums2.length;
int totalLength = length1 + length2;
if( totalLength % 2 == 1){
int midIndex = totalLength /2;
double median = getKthElement( nums1,nums2, midIndex + 1);
return median;
}else{
int midIndex1 = totalLength / 2 - 1;
int midIndex2 = totalLength / 2;
double median =(getKthElement(nums1, nums2, midIndex1 + 1) +
getKthElement(nums1, nums2, midIndex2 + 1)) / 2.0;
return median;
}
}
public double getKthElement(int [] nums1, int [] nums2, int k){
int length1 = nums1.length;
int length2 = nums2.length;
int index1 = 0, index2 = 0;
while(true){
if (index1 == length1){
return nums2[index2 + k - 1];
}
if (index2 == length2){
return nums1[index1 + k - 1];
}
if (k == 1){
return Math.min(nums1[index1],nums2[index2]);
}
int half = k / 2;
int newIndex1 = Math.min(index1 + half, length1) - 1;
int newIndex2 = Math.min(index2 + half, length2) - 1;
int pivot1 = nums1[newIndex1], pivot2 = nums2[newIndex2];
if(pivot1 <= pivot2){
k -= (newIndex1 - index1 + 1);
index1 = newIndex1 + 1;
}else{
k -= (newIndex2 - index2 + 1);
index2 = newIndex2 + 1;
}
}

}```

方法二：

```public double findMedianSortedArrays(int[] nums1, int[] nums2) {

int m = nums1.length;
int n = nums2.length;
if( m > n ){
int [] temp = nums1;
nums1 = nums2;
nums2 = temp;
int tmp = m;
m = n;
n = tmp;
}
int iMin = 0, iMax = m, halfLen = (m + n + 1)/2;
while( iMin <= iMax ){
int i = (iMin + iMax) / 2;
int j = halfLen - i;
if( i < iMax && nums2[j - 1] > nums1[i]){
iMin = i + 1;  //i is too small
}else if( i > iMin && nums1[i - 1] > nums2[j]){
iMax = i - 1;  //i is too big
}else{
int maxLeft = 0;
if ( i == 0){
maxLeft = nums2[j-1];
}else if ( j == 0 ){
maxLeft = nums1[i-1];
}else{
maxLeft = Math.max(nums1[i - 1], nums2[j - 1]);
}
if ( (m + n) %2 == 1){
return maxLeft;
}
int minRight = 0;
if (i == m) { minRight = nums2[j]; }
else if (j == n) { minRight = nums1[i]; }
else { minRight = Math.min(nums2[j], nums1[i]); }

return (maxLeft + minRight) / 2.0;
}
}
return 0.0;
}```

https://leetcode.com/problems/median-of-two-sorted-arrays/

https://leetcode-cn.com/problems/median-of-two-sorted-arrays

4. 寻找两个正序数组的中位数 Median of Two Sorted Arrays

(0)
(0)