GeniusOfCX

导航

leetcode 15 rust

题目

编程语言

rust

注意点

去重条件 (i>0 && nums[i] == nums[i-1])

rust 排序需要获得所有权,vec没有实现copy(trait)所以需要克隆

rust vec.sort()的排序是稳定的,vec.sort_unstable()排序是不稳定的

代码

pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
    let mut res:Vec<Vec<i32>> = Vec::new();
    if nums.len() < 3 {
        return res;
    }
    let mut nums2 = nums.clone();
    nums2.sort_unstable();
    if nums2[0] > 0 {
        return res;
    }
    for i in 0..(nums2.len()-2) {
        let target = -nums2[i];
        if i > 0 && nums2[i] == nums2[i-1] {
            continue;
        }
        let mut l = i+1;
        let mut r = nums2.len()-1;
        while l < r {
            let temp = nums2[l] + nums2[r];
            match temp.cmp(&target) {
                std::cmp::Ordering::Equal => {
                    res.push(vec![-target,nums2[l],nums2[r]]);
                    while l < r && nums2[l] == nums2[l+1] {
                        l = l + 1;
                    }
                    while l < r && nums2[r] == nums2[r-1] {
                        r = r - 1;
                    }
                    l = l + 1;
                    r = r - 1;
                },
                std::cmp::Ordering::Less => {
                    l = l + 1
                },
                std::cmp::Ordering::Greater => {
                    r= r - 1
                },
            }
        }
    }
    res
}

测试

#[cfg(test)]
mod tests{
    use super::*;
    #[test]
    fn test_1(){
        assert_eq!(three_sum(vec![-1,0,1,2,-1,-4]),vec![vec![-1,-1,2],vec![-1,0,1]]);
    }
    #[test]
    fn test_2(){
        assert_eq!(three_sum(vec![]),Vec::<Vec<i32>>::new());
    }
    #[test]
    fn test_3(){
        assert_eq!(three_sum(vec![0]),Vec::<Vec<i32>>::new());
    }
}

posted on 2021-04-08 09:56  GeniusOfCX  阅读(86)  评论(0编辑  收藏  举报