leet-code/intersection-of-two-arrays-ii/sol.rs

26 lines
956 B
Rust

use std::collections::HashMap;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// Get longer & shorter side to optimise memory a little
let (longer, shorter) = if nums1.len() > nums2.len() {
(nums1.into_iter(), nums2.into_iter())
} else {
(nums2.into_iter(), nums1.into_iter())
};
// Get counts of each element of shorter vector
let mut counts: HashMap<i32, i32> = shorter
.fold(HashMap::new(), |mut counts, n| {
counts.insert(n, 1 + *counts.get(&n).unwrap_or(&0));
counts
});
// Filter longer vector using the counts of the elements of the shorter vector
longer
.filter(|n| {
let count = *counts.get(n).unwrap_or(&0);
counts.insert(*n, count - 1);
count.is_positive()
})
.collect()
}
}