-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4.java
More file actions
35 lines (28 loc) · 1.15 KB
/
4.java
File metadata and controls
35 lines (28 loc) · 1.15 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
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
if(nums1.length > nums2.length)
return findMedianSortedArrays(nums2, nums1);
int m = nums1.length;
int n = nums2.length;
int low = 0, high = m;
while(low <= high){
int cut1 = (low + high) / 2;
int cut2 = (m + n + 1) / 2 - cut1;
int left1 = (cut1 == 0) ? Integer.MIN_VALUE : nums1[cut1 - 1];
int right1 = (cut1 == m) ? Integer.MAX_VALUE : nums1[cut1];
int left2 = (cut2 == 0) ? Integer.MIN_VALUE : nums2[cut2 - 1];
int right2 = (cut2 == n) ? Integer.MAX_VALUE : nums2[cut2];
if(left1 <= right2 && left2 <= right1){
if((m + n) % 2 == 0)
return (Math.max(left1, left2) + Math.min(right1, right2)) / 2.0;
else
return Math.max(left1, left2);
}
else if(left1 > right2)
high = cut1 - 1;
else
low = cut1 + 1;
}
return 0.0;
}
}