FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Add: Median of Two Sorted Arrays · OmarShawky1/Problem-Solving-Map@f44adb9 · GitHub

Repository navigation

Commit f44adb9

Browse files
committed
Add: Median of Two Sorted Arrays
1 parent 3e9cf98 commit f44adb9

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package arrays.sortingAndSearching.binarySearch;
2+
3+
public class FindMedianSortedArrays {
4+
5+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
6+
// nums1 is X and nums2 is Y
7+
8+
// Ensure nums1 is the smaller array
9+
if (nums1.length > nums2.length) return findMedianSortedArrays(nums2, nums1);
10+
11+
// Pointers for nums1
12+
int start = 0, end = nums1.length;
13+
14+
while (start <= end) {
15+
int partitionX = (start + end) / 2; // Middle, no need for overflow way of writing it.
16+
int partitionY = (nums1.length + nums2.length + 1) / 2 - partitionX; // 1 is for odd length case.
17+
18+
// If partitionX is 0 it means nothing is there on left side. Use -INF for maxLeftX
19+
// If partitionX is length of input then there is nothing on right side. Use +INF for minRightX
20+
int maxLeftX = partitionX > 0 ? nums1[partitionX - 1] : Integer.MIN_VALUE;
21+
int minRightX = partitionX < nums1.length ? nums1[partitionX] : Integer.MAX_VALUE;
22+
int maxLeftY = partitionY > 0 ? nums2[partitionY - 1] : Integer.MIN_VALUE;
23+
int minRightY = partitionY < nums2.length ? nums2[partitionY] : Integer.MAX_VALUE;
24+
25+
// Base case, if partitions is found, return
26+
if (maxLeftX <= minRightY && maxLeftY <= minRightX){
27+
// If length is odd, take max of maxes
28+
if ((nums1.length + nums2.length) % 2 != 0) return Math.max(maxLeftX, maxLeftY);
29+
// else, take the average of (max of maxes and min of mins
30+
else return (double) (Math.max(maxLeftX, maxLeftY) + Math.min(minRightX, minRightY)) / 2;
31+
}
32+
33+
// If left value of X is more than right value of Y, We need to move right
34+
if (maxLeftX > minRightY) end = partitionX - 1;
35+
else start = partitionX + 1;
36+
}
37+
38+
throw new IllegalArgumentException("Input arrays are not sorted");
39+
}
40+
41+
public static void test() {
42+
FindMedianSortedArrays f = new FindMedianSortedArrays();
43+
44+
assert f.findMedianSortedArrays(new int[]{1, 3}, new int[]{2}) == 2.0;
45+
assert f.findMedianSortedArrays(new int[]{1, 2}, new int[]{3, 4}) == 2.5;
46+
assert f.findMedianSortedArrays(new int[]{2}, new int[]{}) == 2;
47+
}
48+
}

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL