-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbugs.java
47 lines (46 loc) · 1.48 KB
/
bugs.java
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
38
39
40
41
42
43
44
45
46
public class bugs{
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
if (m > n) {
int[] temp = nums1;
nums1 = nums2;
nums2 = temp;
int tempLen = m;
m = n;
n = tempLen;
}
int iMin = 0, iMax = m;
int halfLen = (m + n + 1) / 2;
double maxOfLeft, minOfRight;
while (iMin <= iMax) {
int i = (iMin + iMax) / 2;
int j = halfLen - i;
if (i < m && nums2[j - 1] > nums1[i]) {
iMin = i + 1;
} else if (i > 0 && nums1[i - 1] > nums2[j]) {
iMax = i - 1;
} else {
if (i == 0) {
maxOfLeft = nums2[j - 1];
} else if (j == 0) {
maxOfLeft = nums1[i - 1];
} else {
maxOfLeft = Math.max(nums1[i - 1], nums2[j - 1]);
}
if ((m + n) % 2 == 1) {
return maxOfLeft;
}
if (i == m) {
minOfRight = nums2[j];
} else if (j == n) {
minOfRight = nums1[i];
} else {
minOfRight = Math.min(nums1[i], nums2[j]);
}
return (maxOfLeft + minOfRight) / 2;
}
}
return 0; // In case the input arrays are not sorted
}
}