File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Version 1: focus on logic
1
2
impl Solution {
2
3
pub fn find_median_sorted_arrays ( mut nums1 : Vec < i32 > , nums2 : Vec < i32 > ) -> f64 {
3
4
for val in nums2 {
@@ -10,3 +11,61 @@ impl Solution {
10
11
}
11
12
}
12
13
}
14
+
15
+ // Version 2: focus on binary search
16
+ impl Solution {
17
+ pub fn find_median_sorted_arrays ( mut nums1 : Vec < i32 > , mut nums2 : Vec < i32 > ) -> f64 {
18
+ let total = nums1. len ( ) + nums2. len ( ) ;
19
+ let half = total / 2 ;
20
+
21
+ if nums1. len ( ) > nums2. len ( ) {
22
+ std:: mem:: swap ( & mut nums1, & mut nums2) ;
23
+ }
24
+
25
+ let mut left = 0 ;
26
+ let mut right = nums1. len ( ) ;
27
+
28
+ while left <= right {
29
+ let mid = left + ( right - left) / 2 ;
30
+ let pointer = half - mid;
31
+
32
+ let base_left = if mid > 0 {
33
+ nums1[ mid - 1 ] as f64
34
+ } else {
35
+ f64:: MIN
36
+ } ;
37
+
38
+ let base_right = if mid < nums1. len ( ) {
39
+ nums1[ mid] as f64
40
+ } else {
41
+ f64:: MAX
42
+ } ;
43
+
44
+ let ref_left = if pointer > 0 {
45
+ nums2[ pointer - 1 ] as f64
46
+ } else {
47
+ f64:: MIN
48
+ } ;
49
+
50
+ let ref_right = if pointer < nums2. len ( ) {
51
+ nums2[ pointer] as f64
52
+ } else {
53
+ f64:: MAX
54
+ } ;
55
+
56
+ if base_left <= ref_right && ref_left <= base_right {
57
+ if total % 2 == 1 {
58
+ return base_right. min ( ref_right) ;
59
+ } else {
60
+ return ( base_left. max ( ref_left) + base_right. min ( ref_right) ) / 2.0 ;
61
+ }
62
+ } else if base_left > ref_right {
63
+ right = mid - 1 ;
64
+ } else {
65
+ left = mid + 1 ;
66
+ }
67
+ }
68
+
69
+ panic ! ( "Arrays are not sorted" ) ;
70
+ }
71
+ }
You can’t perform that action at this time.
0 commit comments