题目
代码
方法1,简单易想法:
有序的合并成一个数组,取其中位数即可。
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums;
int m = nums1.length;
int n = nums2.length;
nums = new int[m + n];
if (m == 0) {
if (n % 2 == 0)
return (nums2[n / 2 - 1] + nums2[n / 2]) / 2.0;
else
return nums2[n / 2];
}else if (n == 0) {
if (m % 2 == 0)
return (nums1[m / 2 - 1] + nums1[m / 2]) / 2.0;
else
return nums1[m / 2];
}else {
int count = 0;
int i = 0 , j = 0;
while(count != m + n) {
if (i == m) {
while (j != n)
nums[count++] = nums2[j++];
break;
}else if (j == n) {
while (i != m)
nums[count++] = nums1[i++];
break;
}else {
if (nums1[i] < nums2[j])
nums[count++] = nums1[i++];
else
nums[count++] = nums2[j++];
}
}
if (count % 2 == 0)
return (nums[count / 2 -1] + nums[count / 2]) / 2.0;
else
return nums[count / 2];
}
}
}
方法2,二分查找
码源
class Solution {
//对于时间复杂度要求是log,一般都是用到了二分查找!
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int length1 = nums1.length, 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, midIndex2 = totalLength / 2;
double median = (getKthElement(nums1, nums2, midIndex1 + 1) + getKthElement(nums1, nums2, midIndex2 + 1)) / 2.0;
return median;
}
}
public int getKthElement(int[] nums1, int[] nums2, int k) {
int length1 = nums1.length, length2 = nums2.length;
int index1 = 0, index2 = 0;
int KthElement = 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;
}
}
}
}