Skip to content

Commit fdb7abb

Browse files
committed
Sync LeetCode submission - Intersection of Two Arrays II (rust)
1 parent 2de74e8 commit fdb7abb

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use std::collections::HashMap;
2+
impl Solution {
3+
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
4+
let mut map = HashMap::new();
5+
for num in nums1 {
6+
add_or_increment(&mut map, num);
7+
}
8+
9+
let mut ans = Vec::new();
10+
11+
for num in nums2 {
12+
match map.get_mut(&num) {
13+
None => continue,
14+
Some(n) => {
15+
if *n != 0 {
16+
ans.push(num);
17+
*n -= 1;
18+
}
19+
}
20+
}
21+
}
22+
ans
23+
}
24+
}
25+
26+
fn add_or_increment(map: &mut HashMap<i32, u16>, num: i32) {
27+
match map.get_mut(&num) {
28+
Some(num) => *num += 1,
29+
None => {
30+
map.insert(num, 1);
31+
}
32+
};
33+
}

0 commit comments

Comments
 (0)