题目描述
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)).
样例
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
思路分析
方法一是最开始的想法。暴力求解,但没注意复杂度,到n2了,运行时超时。
方法二:看到有序数组,查找某个值,自然是要用二分查找。有关二分查找,可以看这个。
代码
方法一:
public double findMedianSortedArrays(int[] nums1, int[] nums2)
{
int[] a = new int[nums1.length+nums2.length];
for(int i=0; i<nums1.length; i++)
{
a[i] = nums1[i];
}
for(int i=0; i<nums2.length; i++)
{
a[i+nums1.length] = nums1[i];
}
Arrays.sort(a);
if(a.length%2==0)
{
return (a[a.length/2]+a[a.length/2-1])/2;
}
else
{
return(a[(a.length-1)/2]);
}
}
方法二:
public double findMedianSortedArrays(int[] nums1, int[] nums2)
{
int m = nums1.length;
int n = nums2.length;
int l = (m+n+1)/2;
int r = (m+n+2)/2;
return (getkey(nums1, 0, nums2, 0, l) + getkey(nums1, 0, nums2, 0, r))/2;
}
public double getkey(int []a, int as, int[] b, int bs, int k)
{
if (as > a.length-1) //分别考虑a,b数组为空的情况
{
return b[bs+k-1];
}
if (bs > b.length-1)
{
return a[as+k-1];
}
if (k==1) //数组内只有一个元素的情况
{
return Math.min(a[as], b[as]);
}
int amid = Integer.MAX_VALUE;
int bmid = Integer.MAX_VALUE;
if (as+k/2-1 <a.length)
{
amid = a[as+k/2-1];
}
if (bs+k/2-1 <b.length)
{
bmid = b[bs+k/2-1];
}
if (amid < bmid) //判断+递归查找
{
return getkey(a, as+k/2, b, bs, k-k/2);
}
else
{
return getkey(a, as, b, bs+k/2, k-k/2);
}
}