@@ -35,36 +35,35 @@ class Solution1 {
35
35
public double findMedianSortedArrays (int [] A , int [] B ) {
36
36
int m = A .length ;
37
37
int n = B .length ;
38
- int l = (m + n + 1 ) / 2 ;
39
- int r = (m + n + 2 ) / 2 ;
38
+ int l = (m + n + 1 ) / 2 ; //left half of the combined median
39
+ int r = (m + n + 2 ) / 2 ; //right half of the combined median
40
+ // If the nums1.length + nums2.length is odd, the 2 function will return the same number
41
+ // Else if nums1.length + nums2.length is even, the 2 function will return the left number and right number that make up a median
40
42
return (getkth (A , 0 , B , 0 , l ) + getkth (A , 0 , B , 0 , r )) / 2.0 ;
41
43
}
42
44
43
45
public double getkth (int [] A , int aStart , int [] B , int bStart , int k ) {
44
- if (aStart > A .length - 1 ) {
45
- return B [bStart + k - 1 ];
46
- }
47
- if (bStart > B .length - 1 ) {
48
- return A [aStart + k - 1 ];
49
- }
50
- if (k == 1 ) {
51
- return Math .min (A [aStart ], B [bStart ]);
52
- }
46
+ // This function finds the Kth element in nums1 + nums2
47
+
48
+ // If nums1 is exhausted, return kth number in nums2
49
+ if (aStart > A .length - 1 ) return B [bStart + k - 1 ];
50
+
51
+ // If nums2 is exhausted, return kth number in nums1
52
+ if (bStart > B .length - 1 ) return A [aStart + k - 1 ];
53
+
54
+ // If k == 1, return the first number
55
+ // Since nums1 and nums2 is sorted, the smaller one among the start point of nums1 and nums2 is the first one
56
+ if (k == 1 ) return Math .min (A [aStart ], B [bStart ]);
53
57
54
58
int aMid = Integer .MAX_VALUE ;
55
59
int bMid = Integer .MAX_VALUE ;
56
- if (aStart + k / 2 - 1 < A .length ) {
57
- aMid = A [aStart + k / 2 - 1 ];
58
- }
59
- if (bStart + k / 2 - 1 < B .length ) {
60
- bMid = B [bStart + k / 2 - 1 ];
61
- }
60
+ if (aStart + k / 2 - 1 < A .length ) aMid = A [aStart + k / 2 - 1 ];
61
+ if (bStart + k / 2 - 1 < B .length ) bMid = B [bStart + k / 2 - 1 ];
62
62
63
- if (aMid < bMid ) {
64
- return getkth (A , aStart + k / 2 , B , bStart , k - k / 2 );// Check: aRight + bLeft
65
- } else {
66
- return getkth (A , aStart , B , bStart + k / 2 , k - k / 2 );// Check: bRight + aLeft
67
- }
63
+ // Throw away half of the array from nums1 or nums2. And cut k in half
64
+ return (aMid < bMid ) ?
65
+ getkth (A , aStart + k / 2 , B , bStart , k - k / 2 ):// Check: aRight + bLeft
66
+ getkth (A , aStart , B , bStart + k / 2 , k - k / 2 );// Check: bRight + aLeft
68
67
}
69
68
}
70
69
0 commit comments