[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
*
*
*/
public double findMedianSortedArray(int[] left, int[] right) {
int LEFT_SIZE = left.length;
int RIGHT_SIZE = right.length;
int[] arr = new int[LEFT_SIZE + RIGHT_SIZE];
int i = 0, j = 0, index = 0;
//俩数组 合并
while (i < LEFT_SIZE && j < RIGHT_SIZE) {
if (left[i] < right[j]) {
arr[index++] = left[i++];
} else {
arr[index++] = right[j++];
}
}
while (i < LEFT_SIZE) {
arr[index++] = left[i++];
}
while (j < RIGHT_SIZE) {
arr[index++] = right[j++];
}
int len = arr.length;
//算排序好的数组 中位数
double result = len % 2 != 0 ? arr[len / 2] : (arr[len / 2 - 1] + arr[len / 2]) / 2.0;
return result;
}