Skip to content

Latest commit

 

History

History
42 lines (37 loc) · 1.1 KB

4.median-of-two-sorted-arrays.md

File metadata and controls

42 lines (37 loc) · 1.1 KB

問題

https://leetcode.com/problems/median-of-two-sorted-arrays/

回答

初回の回答:

impl Solution {
    pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
        let mut combined = Vec::new();
        let (mut i, mut j) = (0, 0);
        while i < nums1.len() || j < nums2.len() {
            let nums1_i = nums1.get(i);
            let nums2_j = nums2.get(j);
            if nums1_i.is_none() {
                combined.push(nums2[j]);
                j += 1;
                continue;
            } else if nums2_j.is_none() {
                combined.push(nums1[i]);
                i += 1;
                continue;
            }

            if nums1_i <= nums2_j {
                combined.push(nums1[i]);
                i += 1;
            } else {
                combined.push(nums2[j]);
                j += 1;
            }
        }
        let length = combined.len();
        if length % 2 == 0 {
            return (f64::from(combined[(length / 2) - 1]) + f64::from(combined[(length / 2)])) / 2.0
        }
        combined[length / 2] as f64
    }
}