Skip to content

Commit 8f5bc07

Browse files
committed
add MedianOfTwoSortedArrays.cpp
1 parent e1cda3d commit 8f5bc07

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include <iostream>
2+
#include <climits>
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
double findMedianSortedArrays(int A[], int m, int B[], int n) {
8+
int mid = (m + n - 1) / 2;
9+
int st = 0, ed = m - 1, i = 0, j = 0;
10+
while (st <= ed) {
11+
i = (st + ed) / 2;
12+
j = mid - i;
13+
14+
int b1 = getVal(B, n, j - 1), b2 = getVal(B, n, j);
15+
if (A[i] >= b1 && A[i] <= b2) {
16+
break;
17+
} else if (A[i] < b1) {
18+
st = i + 1;
19+
} else if (A[i] > b2) {
20+
ed = i - 1;
21+
}
22+
}
23+
24+
if (st <= ed) {
25+
if ((m + n) & 1) {
26+
return A[i];
27+
} else {
28+
int o = min(getVal(A, m, i + 1), getVal(B, n, j));
29+
return (A[i] + o) * 0.5;
30+
}
31+
} else {
32+
return findMedianSortedArrays(B, n, A, m);
33+
}
34+
}
35+
36+
int getVal(int a[], int n, int idx) {
37+
if (idx < 0) return INT_MIN;
38+
else if (idx >= n) return INT_MAX;
39+
else return a[idx];
40+
}
41+
};

0 commit comments

Comments
 (0)