[LintCode]2つのソート配列の中位数
5477 ワード
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 here
10 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 };