forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindMedianSortedArrays.cpp
More file actions
41 lines (37 loc) · 1.05 KB
/
findMedianSortedArrays.cpp
File metadata and controls
41 lines (37 loc) · 1.05 KB
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
41
#include <iostream>
#include <climits>
using namespace std;
class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
int mid = (m + n - 1) / 2;
int st = 0, ed = m - 1, i = 0, j = 0;
while (st <= ed) {
i = (st + ed) / 2;
j = mid - i;
int b1 = getVal(B, n, j - 1), b2 = getVal(B, n, j);
if (A[i] >= b1 && A[i] <= b2) {
break;
} else if (A[i] < b1) {
st = i + 1;
} else if (A[i] > b2) {
ed = i - 1;
}
}
if (st <= ed) {
if ((m + n) & 1) {
return A[i];
} else {
int o = min(getVal(A, m, i + 1), getVal(B, n, j));
return (A[i] + o) * 0.5;
}
} else {
return findMedianSortedArrays(B, n, A, m);
}
}
int getVal(int a[], int n, int idx) {
if (idx < 0) return INT_MIN;
else if (idx >= n) return INT_MAX;
else return a[idx];
}
};