Skip to content

Commit 2ee7edf

Browse files
committed
add: FindTheMedianFromTwoSortedArrays
1 parent f3a2e5d commit 2ee7edf

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.Set;
2+
3+
public class FindTheMedianFromTwoSortedArrays {
4+
public float findTheMedianFromTwoSortedArrays(int[] nums1, int[] nums2) {
5+
// Optimization: ensure 'nums1' is the smaller array.
6+
if (nums2.length < nums1.length) {
7+
int[] tmp = nums1;
8+
nums1 = nums2;
9+
nums2 = tmp;
10+
}
11+
int m = nums1.length;
12+
int n = nums2.length;
13+
int halfTotalLen = (m + n) / 2;
14+
int left = 0;
15+
int right = m - 1;
16+
// A median always exists in a non-empty array, so continue binary search until
17+
// it’s found.
18+
while (true) {
19+
// Reminder: integer division rounds toward 0 in Java
20+
// ex: -1 / 2 = 0
21+
int L1Index = Math.floorDiv(left + right, 2);
22+
int L2Index = halfTotalLen - (L1Index + 1) - 1;
23+
// Set to -infinity or +infinity if out of bounds.
24+
float L1 = L1Index < 0 ? Float.NEGATIVE_INFINITY : nums1[L1Index];
25+
float R1 = L1Index >= m - 1 ? Float.POSITIVE_INFINITY : nums1[L1Index + 1];
26+
float L2 = L2Index < 0 ? Float.NEGATIVE_INFINITY : nums2[L2Index];
27+
float R2 = L2Index >= n - 1 ? Float.POSITIVE_INFINITY : nums2[L2Index + 1];
28+
// If 'L1 > R2', then 'L1' is too far to the right. Narrow the search space
29+
// toward the left.
30+
if (L1 > R2) {
31+
right = L1Index - 1;
32+
}
33+
// If 'L2 > R1', then 'L1' is too far to the left. Narrow the search space
34+
// toward the right.
35+
else if (L2 > R1) {
36+
left = L1Index + 1;
37+
}
38+
// If both 'L1' and 'L2' are less than or equal to both 'R1' and 'R2', we
39+
// found the correct slice.
40+
else {
41+
if ((m + n) % 2 == 0) {
42+
return (Math.max(L1, L2) + Math.min(R1, R2)) / 2.0;
43+
} else {
44+
return Math.min(R1, R2);
45+
}
46+
}
47+
}
48+
}
49+
}

0 commit comments

Comments
 (0)