[閒聊] 每日leetcode 75 - Day8 - 4

作者: yam276 ('_')   2025-06-10 15:28:20
2215. 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]
}
}

Links booklink

Contact Us: admin [ a t ] ucptt.com