1
- /*Brute-force solution (Linear time)*/
2
-
1
+ /*Brute-force solution (Linear)*/
2
+ /*
3
+ // Runtime: O(m+n)
4
+ // Extra Space: O(m+n)
5
+ //
3
6
class Solution {
4
7
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
5
8
int m = nums1.length;
@@ -18,3 +21,58 @@ public double findMedianSortedArrays(int[] nums1, int[] nums2) {
18
21
} else return (float)nums[(m+n-1)/2];
19
22
}
20
23
}
24
+ */
25
+ /* Optimized solution (Logarithmic) */
26
+
27
+ // Runtime: O(log(min(m,n)))
28
+ // Extra Space: O(1)
29
+
30
+ class Solution {
31
+ public double findMedianSortedArrays (int [] nums1 , int [] nums2 ) {
32
+ int m = nums1 .length ;
33
+ int n = nums2 .length ;
34
+
35
+ if (m > n ){
36
+ return findMedianSortedArrays (nums2 , nums1 );
37
+ }
38
+
39
+ int total = m + n ;
40
+ int half = (total + 1 ) / 2 ;
41
+
42
+ int left = 0 ;
43
+ int right = m ;
44
+
45
+ var result = 0.0 ;
46
+
47
+ while (left <= right ){
48
+ int i = left + (right - left ) / 2 ;
49
+ int j = half - i ;
50
+
51
+ // get the four points around possible median
52
+ int left1 = (i > 0 ) ? nums1 [i - 1 ] : Integer .MIN_VALUE ;
53
+ int right1 = (i < m ) ? nums1 [i ] : Integer .MAX_VALUE ;
54
+ int left2 = (j > 0 ) ? nums2 [j - 1 ] : Integer .MIN_VALUE ;
55
+ int right2 = (j < n ) ? nums2 [j ] : Integer .MAX_VALUE ;
56
+
57
+ // partition is correct
58
+ if (left1 <= right2 && left2 <= right1 ) {
59
+ // even
60
+ if (total % 2 == 0 ) {
61
+ result = (Math .max (left1 , left2 ) + Math .min (right1 , right2 )) / 2.0 ;
62
+ // odd
63
+ } else {
64
+ result = Math .max (left1 , left2 );
65
+ }
66
+ break ;
67
+ }
68
+ // partition is wrong (update left/right pointers)
69
+ else if (left1 > right2 ) {
70
+ right = i - 1 ;
71
+ } else {
72
+ left = i + 1 ;
73
+ }
74
+ }
75
+
76
+ return result ;
77
+ }
78
+ }
0 commit comments