-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedian of Two Sorted Arrays.txt
More file actions
29 lines (27 loc) · 977 Bytes
/
Median of Two Sorted Arrays.txt
File metadata and controls
29 lines (27 loc) · 977 Bytes
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
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if ((m+n)%2)
return findKth(A, m, B, n, (m+n+1)/2);
else
return (findKth(A, m, B, n, (m+n)/2) + findKth(A, m, B, n, (m+n)/2+1))/(double)2;
}
int findKth(int A[], int m, int B[], int n, int k) {
int i = ((double)m/(m+n))*(k-1);
int j = (k-1) - i;
int ai_1 = (i==0)?INT_MIN:A[i-1];
int bj_1 = (j==0)?INT_MIN:B[j-1];
int ai = (i==m)?INT_MAX:A[i];
int bj = (j==n)?INT_MAX:B[j];
if ((ai_1 <= bj) && (bj <= ai))
return bj;
if ((bj_1 <= ai) && (ai <= bj))
return ai;
if (ai < bj)
return findKth(A + i + 1, m - i - 1, B, n, k - i - 1);
else
return findKth(A, m, B + j + 1, n - j - 1, k - j - 1);
}
};