1. 程式人生 > >4. Median of Two Sorted Arrays

4. Median of Two Sorted Arrays

中間 比較 median log pub math span pan osi

一、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