Skip to content

Commit a8fdfcb

Browse files
committed
Updated median of two sorted arrs
1 parent 2eacd84 commit a8fdfcb

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

Hard/MedianOfTwoSortedArrs.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,26 @@
77
*/
88
class MedianOfTwoSortedArrs {
99
public static void main(String[] args) {
10-
MedianOfTwoSortedArrs median = new MedianOfTwoSortedArrs();
10+
MedianOfTwoSortedArrs m = new MedianOfTwoSortedArrs();
1111
int[] A = {1, 2, 3, 4, 5};
1212
int[] B = {2, 4, 5, 6, 7};
13-
System.out.println(median.findMedianSortedArrays(A, B));
13+
System.out.println(m.findMedianSortedArrays(A, B));
1414
}
1515

1616
/**
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
1822
*/
1923
public double findMedianSortedArrays(int[] A, int[] B) {
2024
int n = A.length;
2125
int m = B.length;
2226
if (n > m) return findMedianSortedArrays(B, A); // shorter array first
2327
int k = (n + m - 1) / 2; // mid position
2428
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]
2630
while (l < r) {
2731
int midA = l + (r - l) / 2; // A[i], avoid overflow
2832
int midB = k - midA; // B[j - 1]

0 commit comments

Comments
 (0)