[LintCode] 兩個排序數組的中位元

來源:互聯網
上載者:User

標籤:

 1 class Solution { 2 public: 3     /** 4      * @param A: An integer array. 5      * @param B: An integer array. 6      * @return: a double whose format is *.5 or *.0 7      */ 8     double findMedianSortedArrays(vector<int> A, vector<int> B) { 9         // write your code here10         int m = A.size(), n = B.size();11         if (m > n) return findMedianSortedArrays(B, A);12         int imin = 0, imax = m, half = (m + n + 1) / 2, i, j, num1, num2;13         while (imin <= imax) {14             i = (imin + imax) / 2;15             j = half - i;16             if (j > 0 && i < m && B[j - 1] > A[i])17                 imin = i + 1;18             else if (i > 0 && j < n && A[i - 1] > B[j])19                 imax = i - 1;20             else {21                 if (!i) num1 = B[j - 1];22                 else if (!j) num1 = A[i - 1];23                 else num1 = max(A[i - 1], B[j - 1]);24                 break;25             }26         }27         if ((m + n) % 2) return num1;28         if (i == m) num2 = B[j];29         else if (j == n) num2 = A[i];30         else num2 = min(A[i], B[j]);31         return (num1 + num2) / 2.0;32     }33 };

 

[LintCode] 兩個排序數組的中位元

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.