Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 875b601

Browse files
author
guangsheng.li01
committed
Solved 0004
1 parent 8dd0925 commit 875b601

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* [0004] median-of-two-sorted-arrays
3+
*/
4+
5+
pub struct Solution {}
6+
7+
// solution impl starts here
8+
9+
use std::cmp::{max, min};
10+
use std::i32::{MAX, MIN};
11+
impl Solution {
12+
pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
13+
let (m, n) = (nums1.len(), nums2.len());
14+
15+
if m > n {
16+
return Solution::find_median_sorted_arrays(nums2, nums1);
17+
}
18+
19+
let (mut low, mut high) = (0, 2 * m);
20+
let (mut lmax1, mut lmax2, mut rmin1, mut rmin2) = (0, 0, 0, 0);
21+
while low <= high {
22+
let c1 = (low + high) / 2;
23+
let c2 = m + n - c1;
24+
25+
lmax1 = if c1 == 0 { MIN } else { nums1[(c1 - 1) / 2] };
26+
lmax2 = if c2 == 0 { MIN } else { nums2[(c2 - 1) / 2] };
27+
rmin1 = if c1 == m * 2 { MAX } else { nums1[c1 / 2] };
28+
rmin2 = if c2 == n * 2 { MAX } else { nums2[c2 / 2] };
29+
30+
if lmax1 > rmin2 {
31+
high = c1 - 1;
32+
} else if lmax2 > rmin1 {
33+
low = c1 + 1;
34+
} else {
35+
break;
36+
}
37+
}
38+
(max(lmax1, lmax2) + min(rmin1, rmin2)) as f64 / 2.0
39+
}
40+
}
41+
42+
// solution impl ends here
43+
44+
// solution tests starts here
45+
46+
#[cfg(test)]
47+
mod tests {
48+
use super::*;
49+
50+
#[test]
51+
fn test_case0() {
52+
assert_eq!(
53+
Solution::find_median_sorted_arrays(vec![1, 3], vec![2]),
54+
2f64
55+
);
56+
}
57+
58+
#[test]
59+
fn test_case1() {
60+
assert_eq!(
61+
Solution::find_median_sorted_arrays(vec![1, 2], vec![3, 4]),
62+
2.5f64
63+
);
64+
}
65+
66+
#[test]
67+
fn test_case2() {
68+
assert_eq!(Solution::find_median_sorted_arrays(vec![], vec![1]), 1f64);
69+
}
70+
}
71+
72+
// solution tests ends here

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ pub mod utils;
55

66
mod a0000_sample;
77
mod a0001_two_sum;
8+
mod a0004_median_of_two_sorted_arrays;
89
mod a0007_reverse_integer;
910
mod a0009_palindrome_number;
1011
mod a0026_remove_duplicates_from_sorted_array;

0 commit comments

Comments
 (0)