Skip to content

Commit f215ea4

Browse files
Merge pull request #163 from vedic-kalra/master
Median of Two Sorted Arrays - With Detailed Explanation
2 parents 0653442 + b0d6c81 commit f215ea4

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

LeetCode/Hard/4. Median of Two Sorted Arrays.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,22 @@
1313
// Output: 2.50000
1414
// Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
1515

16+
/*Suppose the two arrays are A and B.
17+
Perform the following variant of binary search first in A then B to find the median.
18+
19+
Start from low = 0, high = |A|, guess i = floor (low + high)/2
20+
For the median m, there should be total half = floor (|A| + |B| + 1) / 2 elements not greater than it.
21+
Since there are i + 1 elements not greater than A[i] in A,
22+
There should be half - (i + 1) elements not greater than A[i] in B.
23+
Denote j = half - i - 2, thus we can compare if B[j] <= A[i] <= B[j + 1] is satisfied. This indicates
24+
That the guess is the correct median.
25+
26+
Otherwise, we can easily tell if the guess is too small or too big, then halve the elements to adjust
27+
the guess.
28+
29+
Fixes #134
30+
*/
31+
1632

1733

1834

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#define min(x, y) (x < y ? x : y)
2+
3+
int odd(int n) { return n & 0x1; }
4+
5+
void swap(int *x, int *y) {
6+
int tmp = *x; *x = *y; *y = tmp;
7+
}
8+
9+
/* median of an array */
10+
double medianof(int A[], int n) {
11+
return odd(n) ? (double) A[n / 2] : (double)(A[ n / 2] + A[n / 2 - 1]) / 2.0;
12+
}
13+
14+
int find(int A[], int m, int B[], int n) {
15+
int l = 0, u = m;
16+
int i, j, half = (m + n + 1) / 2;
17+
if (!A || m == 0)
18+
return medianof(B, n);
19+
if (!B || n == 0)
20+
return medianof(A, m);
21+
while (l < u) {
22+
i = (l + u) / 2;
23+
j = half - i - 2;
24+
if (j < 0 || j >= n) {
25+
if (j == -1 && A[i] <= B[0])
26+
return i; /* found */
27+
if (j >= n )
28+
l = i + 1; /* too small */
29+
else
30+
u = i; /* too big */
31+
} else {
32+
if (B[j]<= A[i] && (j == n - 1 || A[i] <= B[j+1]))
33+
return i; /* found */
34+
else if (A[i] < B[j])
35+
l = i + 1; /* too small */
36+
else
37+
u = i; /* too big */
38+
}
39+
}
40+
return -1;
41+
}
42+
43+
double findMedianSortedArrays(int A[], int m, int B[], int n) {
44+
int i, j, k, *C;
45+
if (!A || m == 0)
46+
return medianof(B, n);
47+
if (!B || n == 0)
48+
return medianof(A, m);
49+
if ((i = find(A, m, B, n)) == -1) {
50+
i = find(B, n, A, m);
51+
C = A; A = B; B = C;
52+
swap(&m, &n);
53+
}
54+
if (odd(m + n))
55+
return (double)A[i];
56+
j = (m + n) / 2 - i - 2;
57+
if (i == m - 1)
58+
k = B[j+1];
59+
else if (j == n - 1)
60+
k = A[i+1];
61+
else
62+
k = min(A[i+1], B[j+1]);
63+
return (double)(A[i] + k) / 2.0;
64+
}

0 commit comments

Comments
 (0)