Skip to content

Commit 3ed7f7d

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 4_Median_of_Two_Sorted_Arrays.java
1 parent f644506 commit 3ed7f7d

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
3+
int m = nums1.length;
4+
int n = nums2.length;
5+
int sum = m + n;
6+
int target = sum / 2;
7+
8+
if (sum % 2 == 0) {
9+
return ((double) findKth(nums1, nums2, 0, 0, target) + findKth(nums1, nums2, 0, 0, target + 1)) / 2;
10+
} else {
11+
return (double) findKth(nums1, nums2, 0, 0, target + 1);
12+
}
13+
}
14+
15+
private int findKth(int[] a, int[] b, int startA, int startB, int k) {
16+
if (startA >= a.length) {
17+
return b[startB + k - 1];
18+
}
19+
if (startB >= b.length) {
20+
return a[startA + k - 1];
21+
}
22+
if (k == 1) {
23+
return Math.min(a[startA], b[startB]);
24+
}
25+
26+
int midAIdx = startA + k / 2 - 1;
27+
int midBIdx = startB + k / 2 - 1;
28+
29+
int midA = (midAIdx >= a.length) ? Integer.MAX_VALUE : a[midAIdx];
30+
int midB = (midBIdx >= b.length) ? Integer.MAX_VALUE : b[midBIdx];
31+
32+
if (midA > midB) {
33+
return findKth(a, b, startA, startB + k / 2, k - k / 2);
34+
} else {
35+
return findKth(a, b, startA + k / 2, startB, k - k / 2);
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)