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
class Solution {
public double findMedianSortedArrays(int A[], int B[]) {
if((A.length+B.length)%2==1)
return findKSortedArrays(A,B,(A.length+B.length)/2+1,0,A.length-1,0,B.length-1);
else
return (findKSortedArrays(A,B,(A.length+B.length)/2,0,A.length-1,0,B.length-1)
+findKSortedArrays(A,B,(A.length+B.length)/2+1,0,A.length-1,0,B.length-1))/2.0;
}
public int findKSortedArrays(int[] nums1, int[] nums2, int k, int i, int i2, int j, int j2){
int m = i2-i+1;
int n = j2-j+1;
if(m>n)
return findKSortedArrays(nums2,nums1,k,j,j2,i,i2);
if(m==0) return nums2[j+k-1];
if(k==1) return Math.min(nums1[i],nums2[j]);
int Pos1 = Math.min(m,k/2);
int Pos2 = k-Pos1;
if(nums1[i+Pos1-1]<nums2[j+Pos2-1]){
return findKSortedArrays(nums1,nums2,k-Pos1,i+Pos1,i2,j,j2+Pos2-1);
}else if(nums1[i+Pos1-1]>nums2[j+Pos2-1]){
return findKSortedArrays(nums1,nums2,k-Pos2,i,i2+Pos1-1,j+Pos2,j2);
}else{
return nums1[i+Pos1-1];
}
}
}
思路:将这道题目转换为在两个排序数组中求第k小的数,只不过在这里k=(m+n)/2,在两个数组中分别选择k/2个元素,如果A[k/2-1]小于B[k/2-1],那么A的前k/2个数一定在k个数之前,所以可以抛弃A中的k/2个数,同理B也一样,在抛弃A的前k/2个数后,别忘了需要更新k的值,k此时变为k-k/2,不过这里有个问题,如果数组中的数不够k/2怎么办呢?我们保持一个数组的元素总是小于另外一个,然后取k/2和剩下数组长度的较小值作为数组元素比较小的那一个数组本次的选择元素个数。