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

    题目

    代码

    pub fn search_range(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let lower = lower_bound(&nums,target);
        let upper = upper_bound(&nums,target);
        if lower > upper {
            return vec![-1,-1];
        }
        vec![lower,upper]
    }
    pub fn lower_bound(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);
            match target.cmp(&nums[mid as usize]){
                std::cmp::Ordering::Less | std::cmp::Ordering::Equal => right = mid - 1,
                std::cmp::Ordering::Greater => left = mid + 1,
            }
        }
        left
    }
    pub fn upper_bound(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);
            match target.cmp(&nums[mid as usize]){
                std::cmp::Ordering::Less => right = mid - 1,
                std::cmp::Ordering::Greater | std::cmp::Ordering::Equal => left = mid + 1,
            }
        }
        right
    }
    

    测试

    #[cfg(test)]
    mod tests{
        use super::*;
        #[test]
        fn test_null(){
            assert_eq!((search_range(vec![],0)),vec![-1,-1]);
        }
        #[test]
        fn test_exist(){
            assert_eq!((search_range(vec![5,7,7,8,8,10],8)),vec![3,4]);
        }
        #[test]
        fn test_not_exist(){
            assert_eq!((search_range(vec![5,7,7,8,8,10],6)),vec![-1,-1]);
        }
    }
    
  • 相关阅读:
    软件测试第三次作业2
    软件测试第三次作业1
    软件测试第二次作业2
    软件测试第二次作业1
    只要你足够努力,好运就会降临。
    实验六
    实验二
    个人简介
    第六次作业
    第五次博客作业
  • 原文地址:https://www.cnblogs.com/GeniusOfCX/p/14631811.html
Copyright © 2011-2022 走看看