2.1.5 Median of Two Sorted Arrays

Link: https://oj.leetcode.com/problems/median-of-two-sorted-arrays/

There are two sorted arrays A and B 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)).

Time: O(logk) = (log(m+n)/2)= O(log(m+n))

Space: O(log(m+n))//why?

這題很難。答案還沒有搞懂。

public class Solution {
    public double findMedianSortedArrays(int A[], int B[]) {
        int m = A.length;
        int n = B.length;
        if((m+n)%2 == 1){
            return helper(A, 0, m-1, B, 0, n-1, (m+n)/2+1);
        }
        else{
            return (double)(helper(A, 0, m-1, B, 0, n-1, (m+n)/2) + helper(A, 0, m-1, B, 0, n-1, (m+n)/2+1))/2.0;
        }
    }
    
    public double helper(int[] A, int aStart, int aEnd, int[] B, int bStart, int bEnd, int k){
        int aLen = aEnd - aStart + 1;
        int bLen = bEnd - bStart + 1;
        if(aLen > bLen){
            return helper(B, bStart, bEnd, A, aStart, aEnd, k);
        }
        if(aLen == 0){
            return B[bStart + k-1];
        }
        if(k == 1){
            return Math.min(A[aStart], B[bStart]);
        }
        int posA = Math.min(k/2, aLen);
        int posB = k - posA;
        if(A[aStart + posA - 1] < B[bStart + posB - 1]){
            return helper(A, aStart+posA, aEnd, B, bStart, bEnd, k-posA);
        }
        else if(A[aStart + posA - 1] > B[bStart + posB - 1]){
            return helper(A, aStart, aEnd, B, bStart+posB, bEnd, k-posB);
        }
        else{
            return A[aStart + posA - 1];
        }
    }
}



發佈了153 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章