Rust 刷 leetcode 的 3sum 问题
leetcode 题目:https://leetcode.com/problems/3sum/
- 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.
- The solution set must not contain duplicate triplets.
- Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
我的解法:
use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; impl Solution { pub fn three_sum(nums: Vec<i32>) -> Vec<Vec<i32>> { let mut ret: HashSet<Vec<i32>> = HashSet::new(); // fix x first for (i, x) in nums.iter().enumerate() { let target = 0 - *x; // then find a 'two_sum' that meets 'target' let mut memoize: HashMap<i32, i32> = HashMap::new(); for y in &nums[i + 1..] { match memoize.get(y) { Some(&z) => { let mut v = vec![*x, *y, z]; v.sort(); ret.insert(v); } None => { memoize.insert(target - *y, *y); } } } } Vec::from_iter(ret.into_iter()) } }
其实有个问题想请教下:
- 我的结果集数据结构定义为了
HashSet<Vec<i32>>
,Vec<i32>
是实现了Hash trait和ParitialEq trait的,但要求Vec内元素的顺序都要一致才能eq;于是我的代码中就有v.sort()
这一句来保证Vec里元素顺序一致方便HashSet去重 - 其实我认为更自然的结果集数据结构应该是
HashSet<HashSet<i32>
,这样就不需要sort,可是编译器告诉我HashSet<i32>
没有实现Hash和Eq trait,找了一些资料也不知道怎么实现…有人知道么?
- 我的结果集数据结构定义为了
学习了