|
| 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 |
0 commit comments