题目: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)).
个人理解:给你两个已经排列好顺序的数组,求这两个数组的中位数。其实就是将这两个数组重新组合成为一个排列好顺序的数组,然后将这个新数组的中位数返回就行了。注意一点就是:当新数组的成员个数为偶数的时候,要将中间那两个数求平均值再将这个平均值返回。当然,这里的解决方案是针对两个数组都是升序排列的,对于一个升序另一个降序,或者两个都是降序的话,就要多一个步骤:将降序的数组反过来。
public class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int len = m + n;
int[] sortedArray;
if (m == 0) {
if (n == 0) {
// 两个数组都为空
return 0;
} else {
// nums1为空,nums2不为空
sortedArray = nums2;
}
} else {
if (n == 0) {
// nums1不为空,nums2为空
sortedArray = nums1;
} else {
// 两个数组都不为空
sortedArray = new int[len];
// 刚开始的时候,两个要比较的数值在其所在的数组中的下标都是0
int currentNums1Index = 0;
int currentNums2Index = 0;
// 刚开始的时候,两个数组都还没结束,可以继续移动指针
boolean nums1Over = false;
boolean nums2Over = false;
for (int i = 0; i < len; i++) {
// 将指针指向的这两个数进行比较,较小的赋给合并的数组
if (nums1[currentNums1Index] < nums2[currentNums2Index]) {
if (!nums1Over) {
// 还没遍历完nums1
sortedArray[i] = nums1[currentNums1Index];
if (currentNums1Index < m - 1) {
currentNums1Index++;
} else {
// 此时已经遍历完nums1数组了
nums1Over = true;
}
} else {
// 已经遍历完nums1数组了
sortedArray[i] = nums2[currentNums2Index];
currentNums2Index++;
}
} else {
if (!nums2Over) {
// 还没遍历完nums2
sortedArray[i] = nums2[currentNums2Index];
if (currentNums2Index < n - 1) {
currentNums2Index++;
} else {
// 此时已经遍历完nums2数组了
nums2Over = true;
}
} else {
// 已经遍历完nums2数组了
sortedArray[i] = nums1[currentNums1Index];
currentNums1Index++;
}
}
}
}
}
int medianIndex = len / 2;
if (len % 2 != 0) {
return sortedArray[medianIndex];
} else {
return (sortedArray[medianIndex - 1] + sortedArray[medianIndex]) / 2.0;
}
}
}