Skip to content

Commit 140b656

Browse files
committed
萤火虫-N4
1 parent d71ed63 commit 140b656

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

src/main/java/N1_100/N4.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package N1_100;
2+
3+
public class N4 {
4+
public double findMedianSortedArrays(int[] A, int[] B) {
5+
int m = A.length;
6+
int n = B.length;
7+
if (m > n) { // to ensure m<=n
8+
int[] temp = A; A = B; B = temp;
9+
int tmp = m; m = n; n = tmp;
10+
}
11+
int iMin = 0, iMax = m, halfLen = (m + n + 1) / 2;
12+
while (iMin <= iMax) {
13+
int i = (iMin + iMax) / 2;
14+
int j = halfLen - i;
15+
if (i < iMax && B[j-1] > A[i]){
16+
iMin = i + 1; // i is too small
17+
}
18+
else if (i > iMin && A[i-1] > B[j]) {
19+
iMax = i - 1; // i is too big
20+
}
21+
else { // i is perfect
22+
int maxLeft = 0;
23+
if (i == 0) { maxLeft = B[j-1]; }
24+
else if (j == 0) { maxLeft = A[i-1]; }
25+
else { maxLeft = Math.max(A[i-1], B[j-1]); }
26+
if ( (m + n) % 2 == 1 ) { return maxLeft; }
27+
28+
int minRight = 0;
29+
if (i == m) { minRight = B[j]; }
30+
else if (j == n) { minRight = A[i]; }
31+
else { minRight = Math.min(B[j], A[i]); }
32+
33+
return (maxLeft + minRight) / 2.0;
34+
}
35+
}
36+
return 0.0;
37+
}
38+
}

0 commit comments

Comments
 (0)