LeetCode 4. Median of Two Sorted Arrays

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]

題目鏈接

題目描述
尋找兩個數組的中位樹
思路
這道題一開始沒有想出來,從網上看的題解,領略到了遞歸的牛X之處。簡單來說就是,每一次查找來縮小一半的範圍。直到一個數組爲0時,即可通過下標找到該值。


public class MedianOfTwoList {
    int lena = 0 ; 
    int lenb = 0; 
    public double findMedianSortedArrays(int A[], int B[]) {
        lena = A.length;
        lenb = B.length;
        int sum = lena+lenb;
        if ( sum%2==1 ) {
            return getKthNumber(A, 0, B, 0, sum/2+1)*1.0;
        } else {
            float s = getKthNumber(A, 0, B, 0, sum/2);
            lena = A.length;
            lenb = B.length;
            float s2 = getKthNumber(A, 0, B, 0, sum/2+1) ;
            return (s+s2)/2.0;
        }
    }
    private int getKthNumber(int[] a,int sa,int[] b,int sb,int k) {
        if ( this.lena-sa >this.lenb-sb ) {
            int temp = this.lena;
            this.lena = this.lenb;
            this.lenb = temp; 
            return getKthNumber(b, sb, a, sa, k);
        }
        else {
            if ( this.lena-sa==0 ) {
                return b[sb+k-1]; 
            } else {
                int m = Integer.min(k/2, this.lena-sa);
                if ( m==0 ) {
                    return a[sa]<b[sb]?a[sa]:b[sb];
                } else {
                    if ( a[sa+m-1]<b[sb+m-1] ) {
                        return getKthNumber(a, sa+m, b, sb, k-m);
                    } else {
                        return getKthNumber(a, sa, b, sb+m, k-m);
                    }
                }
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章