|
7 | 7 | */
|
8 | 8 | class MedianOfTwoSortedArrs {
|
9 | 9 | public static void main(String[] args) {
|
10 |
| - MedianOfTwoSortedArrs median = new MedianOfTwoSortedArrs(); |
| 10 | + MedianOfTwoSortedArrs m = new MedianOfTwoSortedArrs(); |
11 | 11 | int[] A = {1, 2, 3, 4, 5};
|
12 | 12 | int[] B = {2, 4, 5, 6, 7};
|
13 |
| - System.out.println(median.findMedianSortedArrays(A, B)); |
| 13 | + System.out.println(m.findMedianSortedArrays(A, B)); |
14 | 14 | }
|
15 | 15 |
|
16 | 16 | /**
|
17 |
| - * |
| 17 | + * Search in shorter array |
| 18 | + * Find 4 possible candidates A[l-1], A[l], B[k-1], B[k-l+1] |
| 19 | + * If total # of items is odd, return the max of A[l-1] and B[k-1], a |
| 20 | + * If total # of items is even, get the min of A[l] and B[k-l+1], b |
| 21 | + * Return the average of a and b |
18 | 22 | */
|
19 | 23 | public double findMedianSortedArrays(int[] A, int[] B) {
|
20 | 24 | int n = A.length;
|
21 | 25 | int m = B.length;
|
22 | 26 | if (n > m) return findMedianSortedArrays(B, A); // shorter array first
|
23 | 27 | int k = (n + m - 1) / 2; // mid position
|
24 | 28 | int l = 0, r = Math.min(k, n); // r is n, NOT n-1, this is important!!
|
25 |
| - // find A[i] > B[j - 1] |
| 29 | + // find A[l] > B[k - l] |
26 | 30 | while (l < r) {
|
27 | 31 | int midA = l + (r - l) / 2; // A[i], avoid overflow
|
28 | 32 | int midB = k - midA; // B[j - 1]
|
|
0 commit comments