1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
| class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int sum = m + n;
if (sum % 2 == 0) {
return (findk(A, m, B, n, sum/2) + findk(A, m, B, n, sum/2 + 1)) / 2;
} else {
return findk(A, m, B, n, sum/2 + 1);
}
}
double 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 B[k-1];
if (n <= 0)
return A[k-1];
if (k == 1) {
if (A[0] < B[0])
return A[0];
else
return B[0];
}
int a = k/2;
if (m < k/2)
a = m;
int b = k - a;
if (A[a-1] == B[b-1])
return A[a-1];
else if (A[a-1] < B[b-1]) {
return findk(A + a, m - a, B, n, k - a);
} else {
return findk(A, m, B + b, n - b, k - b);
}
}
};
|