• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

leetcode 15 rust

开发技术 开发技术 2周前 (04-07) 7次浏览

题目

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 mut 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 mut 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![]);
    }
    #[test]
    fn test_3(){
        assert_eq!(three_sum(vec![0]),vec![]);
    }
}

程序员灯塔
转载请注明原文链接:leetcode 15 rust
喜欢 (0)