原题网址:https://leetcode.com/problems/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)).
方法:采用二分法查找。
public class Solution {
private int median(int[] nums1, int[] nums2, int k) {
if (nums1.length == 0) return -1;
if (nums2.length == 0) return k;
int i=0, j=nums1.length-1;
while (i<=j) {
int m = (i+j)/2;
int n = k-m;
if (n < 0) j=m-1;
else if (n>nums2.length) i=m+1;
else if (n == nums2.length) {
if (nums2[n-1] <= nums1[m]) return m;
i=m+1;
} else if (n == 0) {
if (nums1[m] <= nums2[n]) return m;
j=m-1;
} else {
if (nums2[n-1] <= nums1[m] && nums1[m] <= nums2[n]) return m;
if (nums2[n-1] > nums1[m]) i=m+1;
if (nums1[m] > nums2[n]) j=m-1;
}
}
return -1;
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int n = nums1.length+nums2.length;
if (n % 2 == 0) {
int m1 = median(nums1, nums2, n/2-1);
int median = 0;
if (m1 != -1) median = nums1[m1]; else median = nums2[median(nums2, nums1, (n-1)/2)];
int m2 = median(nums1, nums2, n/2);
if (m2 != -1) median += nums1[m2]; else median += nums2[median(nums2, nums1, n/2)];
return (double)median/2;
} else {
int m = median(nums1, nums2, (n-1)/2);
if (m != -1) return nums1[m];
return nums2[median(nums2, nums1, (n-1)/2)];
}
}
}
方法二:递归。
public class Solution {
private int find(int[] a, int af, int at, int[] b, int k) {
if (af > at) return -1;
if (b.length == 0) {
if (af <= k && k <= at) return k;
return -1;
}
int m = (af + at) / 2;
int n = k - m;
if (n == b.length) {
if (b[n-1] <= a[m]) return m;
return find(a, m + 1, at, b, k);
}
if (n == 0) {
if (a[m] <= b[n]) return m;
return find(a, af, m - 1, b, k);
}
if (b[n - 1] <= a[m] && a[m] <= b[n]) return m;
if (b[n - 1] > a[m]) return find(a, m + 1, at, b, k);
return find(a, af, m - 1, b, k);
}
private int kth(int[] nums1, int[] nums2, int k) {
for(int i = 0; i < 2; i ++) {
int af = Math.max(0, k - nums2.length);
int at = Math.min(k, nums1.length - 1);
int m = find(nums1, af, at, nums2, k);
if (m != -1) return nums1[m];
int[] temp = nums1;
nums1 = nums2;
nums2 = temp;
}
return 0;
}
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if ((nums1.length + nums2.length) % 2 == 1) {
int k = (nums1.length + nums2.length) / 2;
return kth(nums1, nums2, k);
} else {
int k = (nums1.length + nums2.length) / 2 - 1;
return (double)(kth(nums1, nums2, k) + kth(nums1, nums2, k + 1)) / 2;
}
}
}