GeniusOfCX

导航

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);
    }
}

posted on 2021-04-01 15:08  GeniusOfCX  阅读(46)  评论(0编辑  收藏  举报