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

    题目

    编程语言

    rust

    注意点

    二分法和33题相似,仅当有数字重复时进行不同的判断

    代码

    pub fn search(nums: Vec<i32>, target: i32) -> bool {
        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 true;
            }
            // nums[left] == nums[mid] 意味着从nums[mid]到nums[right]到nums[left]的值都相等
            if nums[mid as usize] == nums[left as usize] {
                left += 1;
                continue;
            }
            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;
                    }
                },
            }
        }
        false
    }
    

    测试

    #[cfg(test)]
    mod tests{
        use super::*;
        #[test]
        fn test_exist(){
            assert_eq!(search(vec![2,5,6,0,0,1,2],0),true);
        }
        #[test]
        fn test_not_exist(){
            assert_eq!(search(vec![2,5,6,0,0,1,2],3),false);
        }
        #[test]
        fn test_null(){
            assert_eq!(search(vec![1],0),false);
        }
    }
    
  • 相关阅读:
    UVaLive 7362 Farey (数学,欧拉函数)
    UVaLive 7361 Immortal Porpoises (矩阵快速幂)
    UVaLive 7359 Sum Kind Of Problem (数学,水题)
    CodeForces 706D Vasiliy's Multiset (字典树查询+贪心)
    负载均衡服务器
    集群-如何理解集群?
    架构规划
    领域模型
    状态图
    E-R图
  • 原文地址:https://www.cnblogs.com/GeniusOfCX/p/14605980.html
Copyright © 2011-2022 走看看