首页 > 代码库 > 4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

一、Description:

  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 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
   
    }
}

 

二、Solutions:

  1、思路:

    本题求中间值,自己采用了一种偷懒的方法,利用 arraycopy 方法,将两个数组放入同一个数组内,并用 sort 函数自动排序,剩下只要输出下标为 median 的数即为中间值了!

public class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int alen = nums1.length;
        int blen = nums2.length;
        int[] c = new int[nums1.length + nums2.length];
        System.arraycopy(nums1, 0, c, 0, alen);

        System.arraycopy(nums2, 0, c, alen, blen);

        Arrays.sort(c);

        int median = (alen + blen) / 2;
        if((alen + blen) == median * 2)
            return ((double)(c[median-1]+c[median]))/2;
        else {
            return c[median];
        }
    }
}

 

2、优化:

  二分法,巧妙的将奇数个数、偶数个数转化为第 m=(aLen+bLen+1)/2、n=(aLen+bLen+2)/2 的数的平均值。再采用递归,依次比较 A[m/2-1] 与 B[m/2-1] 的大小,若 A 大,则 b 下标从m/2-1 开始,依次类推!时间复杂度应该是 logN

public class Solution {
    public double findMedianSortedArrays(int[] a, int[] b) {
        int m = (a.length + b.length + 1) /2;
        int n = (a.length + b.length + 2) /2;

        return (getMedianByPosition(a, 0, b, 0, m) + getMedianByPosition(a, 0, b, 0, n))/2.0;
    }
    
     /*
        aStart\bStart: 下标, 从0开始
        n: 位置,从1开始
     */
    private static int getMedianByPosition(int[] a, int aStart, int[] b, int bStart, int n) {

        if(aStart > a.length - 1) return b[bStart + n - 1];
        if(bStart > b.length - 1) return a[aStart + n - 1];
        if(n == 1) return Math.min(a[aStart], b[bStart]);

        int aMedian = Integer.MAX_VALUE, bMedian = Integer.MAX_VALUE;

        if(a.length > aStart + n/2 - 1 ) aMedian = a[aStart + n/2 - 1];
        if(b.length > bStart + n/2 - 1 ) bMedian = b[bStart + n/2 - 1];

        if(aMedian > bMedian) {
            return getMedianByPosition(a, aStart, b, bStart + n/2 , n - n/2);
        }
        else {
            return getMedianByPosition(a, aStart + n/2, b, bStart , n -n/2);
        }
    }
}

 

三、 总结:

  第二种方法看了很久,才看明白! 自己对于递归真的不熟悉!

4. Median of Two Sorted Arrays