Median of Two Sorted Arrays[leetcode] O(nlogn)的兩種思路,leetcodenlogn

來源:互聯網
上載者:User

Median of Two Sorted Arrays[leetcode] O(nlogn)的兩種思路,leetcodenlogn

設兩個數組分別為A和B,size為as和bs。原問題可以轉化為兩個排序數組求第k大的問題。

還是兩種思路:

比較A[as/2]和B[bs/2],每次拋棄A或者B的一半

代碼如下:

double findMedianSortedArrays(int A[], int m, int B[], int n) {        int total = m + n;        if (total%2)            return findK(A,m,B,n,(total + 1)/2);        else            return (findK(A,m,B,n,total/2) + findK(A,m,B,n,total/2 + 1)) / 2.0;    }        int findK(int A[], int m, int B[], int n, int k)    {        if (m == 0)            return findK(B, n, k);        if (n == 0)            return findK(A, m, k);        if (A[m/2] > B[n/2])            return findK(B,n,A,m,k);        int mid = m/2 + n/2 + 1;        if (k <= mid)            return findK(A, m, B, n/2, k);        if (k > mid)            return findK(A + m/2 + 1, m - m/2 - 1, B, n, k - m/2 - 1);    }        int findK(int A[], int m, int k)    {        return A[k-1];    }


第二種思路更簡單,但是注意各種特殊情況的處理。比較A[k/2]和B[k/2],每次拋棄k的一半

代碼如下:

double findMedianSortedArrays(int A[], int m, int B[], int n) {        int total = m + n;        if (total%2)            return findK(A,m,B,n,(total + 1)/2);        else            return (findK(A,m,B,n,total/2) + findK(A,m,B,n,total/2 + 1)) / 2.0;    }        int findK(int A[], int m, int B[], int n, int k)    {        if (m > n)            return findK(B,n,A,m,k);        if (m == 0)            return findK(B, n, k);        if (k == 1)            return A[0] < B[0] ? A[0] : B[0];        int pa = (k/2 < m? k/2:m);        int pb = k - pa;        if (A[pa - 1] > B[pb - 1])            return findK(A,m,B + pb,n - pb,k - pb);        if (A[pa - 1] < B[pb - 1])            return findK(A + pa,m - pa,B,n,k - pa);        if (A[pa - 1] == B[pb - 1])            return A[pa - 1];    }        int findK(int A[], int m, int k)    {        return A[k-1];    }





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.