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)).

You may assume nums1 and nums2 cannot be both empty.

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

难点主要在于复杂度的要求,logn的复杂度我们就会想到二分查找,二分查找本质上就是对一个有序值的寻找过程,会比遍历的寻找合适值寻找复杂度更低,两个数组都做二分查找的值并没什么意义,我们需要想到一个隐藏条件
oooxxx
ooooxxxx
寻找中位数其实就是剔除比较小的数,而这些小的数都在整个数组的左边,且个数是固定的。

public double findMedianSortedArrays(int[] nums1, int[] nums2) {
    int l1=nums1.length;
    int l2=nums2.length;
    if(l1>l2) return findMedianSortedArrays(nums2,nums1);
    int left=0;
    int right=l1;
    int need=(l1+l2-1)/2;
    while(left<=right){
        int count1=(left+right)/2;
        int count2=need-count1;
        if(count1<l1 && count2>=1 && nums1[count1]<nums2[count2-1]) left=count1+1;
        else if(count1>=1 && nums2[count2]<nums1[count1-1]) right=count1-1;
        else{
            if((l1+l2)%2==1){
                int[] array=new int[]{count1>=l1?Integer.MAX_VALUE:nums1[count1],count2>=l2?Integer.MAX_VALUE:nums2[count2]};
                Arrays.sort(array);
                return (double) (array[0]);
            }else{
                int[] array=new int[]{count1>=l1?Integer.MAX_VALUE:nums1[count1],count2>=l2?Integer.MAX_VALUE:nums2[count2],count1+1>=l1?Integer.MAX_VALUE:nums1[count1+1],count2+1>=l2?Integer.MAX_VALUE:nums2[count2+1]};
                Arrays.sort(array);
                return (double) (array[0]+array[1])/2.0;
            }    
        }
    }
    return 0.0;
}

程浩
21 声望2 粉丝