精華區beta Marginalman 關於我們 聯絡資訊
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] } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.48.170 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1749540502.A.45F.html