楼主:
yam276 ('_')
2025-06-10 15:28:202215. Find the Difference of Two Arrays
题目:
找两个整数阵列的差集
思路:
用 HashSet 的去重复特性
先蒐集起来 然后比较
虽然有内建的 .difference()
但还是自己做比较好
题目都已经简单版了
用 .iter().filter()
另外要 .cloned() 再 .collect()
没有 .cloned() 蒐集到的会是 Vec<&i32>
Code:
use std::collections::HashSet;
impl Solution {
pub fn find_difference(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<Vec<i32>>
{
let mut hash1 = HashSet::new();
let mut hash2 = HashSet::new();
for num in nums1 {
hash1.insert(num);
}
for num in nums2 {
hash2.insert(num);
}
let diff1 = hash1
.iter()
.filter(|&x| !hash2.contains(x))
.cloned()
.collect();
let diff2 = hash2
.iter()
.filter(|&x| !hash1.contains(x))
.cloned()
.collect();
vec![diff1, diff2]
}
}