forked from dimpeshmalviya/JavaBasicPrograms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMedianOfTwoSortedArrays.java
More file actions
37 lines (32 loc) · 1.37 KB
/
MedianOfTwoSortedArrays.java
File metadata and controls
37 lines (32 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class MedianOfTwoSortedArrays {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length)
return findMedianSortedArrays(nums2, nums1);
int x = nums1.length, y = nums2.length;
int low = 0, high = x;
while (low <= high) {
int partitionX = (low + high) / 2;
int partitionY = (x + y + 1) / 2 - partitionX;
int maxX = (partitionX == 0) ? Integer.MIN_VALUE : nums1[partitionX - 1];
int maxY = (partitionY == 0) ? Integer.MIN_VALUE : nums2[partitionY - 1];
int minX = (partitionX == x) ? Integer.MAX_VALUE : nums1[partitionX];
int minY = (partitionY == y) ? Integer.MAX_VALUE : nums2[partitionY];
if (maxX <= minY && maxY <= minX) {
if ((x + y) % 2 == 0)
return ((double)Math.max(maxX, maxY) + Math.min(minX, minY)) / 2;
else
return Math.max(maxX, maxY);
} else if (maxX > minY) {
high = partitionX - 1;
} else {
low = partitionX + 1;
}
}
throw new IllegalArgumentException();
}
public static void main(String[] args) {
int[] nums1 = {1, 3};
int[] nums2 = {2};
System.out.println(findMedianSortedArrays(nums1, nums2));
}
}