/
single_map.rs
50 lines (39 loc) · 1.24 KB
/
single_map.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
pub struct Solution;
// ------------------------------------------------------ snip ------------------------------------------------------ //
use std::collections::hash_map::Entry;
use std::collections::HashMap;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut nums2_count = HashMap::new();
for num in nums2 {
nums2_count.entry(num).and_modify(|count| *count += 1).or_insert(1);
}
let mut nums1 = nums1;
nums1.retain(|num| {
if let Entry::Occupied(entry) = nums2_count.entry(*num) {
if *entry.get() == 1 {
entry.remove();
} else {
*entry.into_mut() -= 1;
}
true
} else {
false
}
});
nums1
}
}
// ------------------------------------------------------ snip ------------------------------------------------------ //
impl super::Solution for Solution {
fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
Self::intersect(nums1, nums2)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}