zoukankan      html  css  js  c++  java
  • leetcode 33 rust

    题目

    编程语言

    rust

    注意点

    二分法

    代码

    pub fn search(nums: Vec<i32>, target: i32) -> i32 {
        let mut left = 0_i32;
        let mut right = (nums.len() as i32) - 1;
        let mut mid;
        while left <= right {
            mid = left + ((right - left) >> 1);
            if nums[mid as usize] == target {
                return mid as i32;
            }
            match nums[mid as usize].cmp(&nums[left as usize]) {
                // left和mid 落在同一数组中
                std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => {
                    // left,mid,right,target在同一数组中
                    if nums[mid as usize] > target && target >= nums[left as usize] {
                        right = mid - 1;
                    // target落在mid和right中间
                    }else if nums[mid as usize] < target || target < nums[left as usize] {
                        left = mid + 1;
                    }
                },
                // left和mid 落在两个数组中
                std::cmp::Ordering::Less => {
                    // left,mid,right,target在同一数组中
                    if nums[mid as usize] < target && target <= nums[right as usize] {
                        left = mid + 1;
                    // target落在left和mid中间
                    }else if nums[mid as usize] > target || target > nums[right as usize] {
                        right = mid - 1;
                    }
                },
            }
        }
        -1
    }
    

    测试

    #[cfg(test)]
    mod tests{
        use super::*;
        #[test]
        fn test_exist(){
            assert_eq!(search(vec![4,5,6,7,0,1,2],0),4);
        }
        #[test]
        fn test_not_exist1(){
            assert_eq!(search(vec![4,5,6,7,0,1,2],3),-1);
        }
        #[test]
        fn test_not_exist2(){
            assert_eq!(search(vec![1],0),-1);
        }
    }
    
  • 相关阅读:
    iOS 跳转app
    Mac下安装Redis图解教程
    高性能图文混排框架,构架顺滑的iOS应用-b
    iOS的layoutSubviews和drawRect方法何时调用
    类似nike+、香蕉打卡的转场动画效果-b
    开源YYKit-b
    轻仿QQ音乐之音频歌词播放、锁屏歌词-b
    数据库事务的四大特性
    拦截器的实现
    ognl表达式
  • 原文地址:https://www.cnblogs.com/GeniusOfCX/p/14605699.html
Copyright © 2011-2022 走看看