用Rust刷leetcode第十五题

Problem

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Notice that the solution set must not contain duplicate triplets.

Example

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]

Example 2:

Input: nums = []
Output: []

Example 3:

Input: nums = [0]
Output: []

Constraints:

  • 0 <= nums.length <= 3000
  • -10^5^ <= nums[i] <= 10^5^

Solution

impl Solution {

    pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> {
        let mut ret: std::collections::HashSet<Vec<i32>> = std::collections::HashSet::new();

        for (i, a) in nums.iter().enumerate() {
            let target = 0 - *a;
            let mut temp: std::collections::HashMap<i32, i32> = std::collections::HashMap::new();

            for b in &nums[i + 1..] {
                match temp.get(b) {
                    Some(&c) => {
                        let mut vtemp = vec![*a, *b, c];
                        vtemp.sort();
                        ret.insert(vtemp);
                    }
                    None => {
                        temp.insert(target - *b, *b);
                    }
                }
            }
        }
        ret.into_iter().collect()
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
119
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商