LeetCode Median of Two Sorted Arrays,leetcodemedian

來源:互聯網
上載者:User

LeetCode Median of Two Sorted Arrays,leetcodemedian

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)).

Show Tags




題意:求兩個有序數組的組成一個新的數組的中位元

思路:題目轉換為求第k大的數,如果總個數是奇數的話,就是求第中間的數了,如果是偶數的話,就是找到兩個中間的,求平均數。

求第k大的數:首先假設我們求的是兩個數組A和B中第k個數,為了我們每次都能折半尋找,我們比較A[k/2]和B[k/2]這兩個數,如果A[k/2-1]<B[k/2-1]的話,說明的是A數組的前k/2個數字都是在最後數組的前k個中,那麼就可以裁掉一點了,依次類推

class Solution {public:    double findMedianSortedArrays(int A[], int m, int B[], int n) {        int size = m + n;        int k = (m + n + 1) / 2;        if (size & 1)            return findKth(A, m, B, n, k);        else return (findKth(A, m, B, n, k) + findKth(A, m, B, n, k+1)) / 2;    }        double findKth(int A[], int m, int B[], int n, int k) {        if (m > n)            return findKth(B, n, A, m, k);        if (m == 0)            return B[k - 1];        if (k == 1)            return A[0] < B[0] ? A[0] : B[0];                int index = k / 2;          int left = index < m ? index : m;          int right = k - left;                    if (A[left - 1] < B[right - 1])                return findKth(A + left, m - left, B, n, right);          else if (A[left - 1] > B[right - 1])             return findKth(A, m, B + right, n - right, left);          else return A[left - 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.