2.1.5 Median of Two Sorted Arrays

来源:互联网 发布:选车软件 编辑:程序博客网 时间:2024/06/16 10:44

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];        }    }}



0 0
原创粉丝点击