• leetcode 153 rust


    题目

    编程语言

    rust

    注意点

    二分法

    right = mid (√) // 因为无法判断nums[mid]是不是最小值

    right = mid - 1(×)

    代码

    pub fn find_min(nums: Vec<i32>) -> i32 {
        let mut left = 0_i32;
        let mut right = (nums.len() as i32) - 1;
        let mut mid;
        while left <= right {
            if nums[left as usize] <= nums[right as usize] {
                return nums[left as usize];
            }
            mid = left + ((right - left) >> 1);
            match nums[left as usize].cmp(&nums[mid as usize]) {
                std::cmp::Ordering::Less | std::cmp::Ordering::Equal => {
                    left = mid + 1;
                },
                std::cmp::Ordering::Greater => {
                    right = mid;
                }
            }
        }
        -1
    }
    

    测试

    #[cfg(test)]
    mod tests{
        use super::*;
        #[test]
        fn test_1(){
            assert_eq!(find_min(vec![3,4,5,1,2]),1);
        }
        #[test]
        fn test_2(){
            assert_eq!(find_min(vec![4,5,6,7,0,1,2]),0);
        }
        #[test]
        fn test_3(){
            assert_eq!(find_min(vec![1]),1);
        }
    }
    
  • 相关阅读:
    MATLAB accumarray
    函数rand,randn,randi
    bsxfun
    sub2ind函数
    MAX
    & 和 &&
    matlab函数int2str, num2str, str2num
    ASCII对照表
    STM32的ADC配置
    单节锂电池基本知识
  • 原文地址:https://www.cnblogs.com/GeniusOfCX/p/14606429.html
Copyright © 2020-2023  润新知