用Rust刷leetcode第十五題

linghuyichong發表於2020-09-05

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 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^
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 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章