rust leetcode median-of-two-sorted-arrays

每日小刷

median-of-two-sorted-arrays/

Runtime Memory
0ms 2.6m

use std::cmp;
impl Solution {
    // 2i + 2j = m+n
    // i = (m+n)/2 - j;
    // (m+n)/2>i
    // n>m 保證j > 0
    pub fn find_median_sorted_arrays(nums1: Vec<i32>, nums2: Vec<i32>) -> f64 {
        let mut iMin = 0;
        let mut iMax = 0;
        let mut m: Vec<i32>;
        let mut n: Vec<i32>;

        if nums1.len() > nums2.len() {
            m = nums2;
            n = nums1;
        } else {
            m = nums1;
            n = nums2;
        }
        iMax = m.len();
        // 二分查找符合條件的變量
        while iMin <= iMax {
            println!("iMin:{:?},iMax:{:?}", iMin, iMax);
            let i = (iMin + iMax) / 2;
            let j = (m.len() + n.len() + 1) / 2 - i;
            if i > iMin && n[j] < m[i - 1] {
                iMax = i - 1;
            } else if i < iMax && m[i] < n[j - 1] {
                iMin = i + 1;
            } else {
                // perfect
                let mut left_max = 0;
                // get left_max
                if i == 0 {
                    left_max = n[j - 1];
                } else if j == 0 {
                    left_max = m[i - 1];
                } else {
                    left_max = cmp::max(n[j - 1], m[i - 1]);
                }

                if (m.len() + n.len()) % 2 == 1 {
                    return left_max as f64;
                }
                let mut right_min = 0;

                if i == m.len() {
                    right_min = n[j];
                } else if j == n.len() {
                    right_min = m[i];
                } else {
                    right_min = cmp::min(n[j], m[i]);
                }
                return (left_max as f64 + right_min as f64) / 2.0;
            }
        }
        0.0
    }
}

好好學(xué)習(xí)rust和基礎(chǔ)算法

目標(biāo):rust工程師

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容