GeniusOfCX

导航

leetcode 34 rust

1.题目

2.编程语言

rust

3.注意点

let mut vec = vec![index]

index 是 usize类型

vec.len() 是 usize类型

4.代码

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
}

5.测试

#[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]);
    }
}

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