MCPcopy Create free account
hub / github.com/StudyRust/leetcode_rust / intersect

Function intersect

350-intersection-of-two-arrays-ii.rs:1–33  ·  view source on GitHub ↗
(nums1: Vec<i32>, nums2: Vec<i32>)

Source from the content-addressed store, hash-verified

1pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
2 use std::collections::HashMap;
3 let mut mmp1 = HashMap::new();
4 let mut mmp2 = HashMap::new();
5 let mut ret = vec![];
6 for num in nums1 {
7 mmp1.entry(num).and_modify(|m|*m += 1).or_insert(1);
8 }
9 for num in nums2 {
10 mmp2.entry(num).and_modify(|m|*m += 1).or_insert(1);
11 }
12 // println!("{:?} {:?}", mmp1, mmp2);
13 if mmp1.len() < mmp2.len() {
14 for (k1, v1) in mmp1 {
15 let v2 = mmp2.get(&k1);
16 if v2.is_some() {
17 for _ in 0..**[v2.unwrap(), &v1].iter().min().unwrap() {
18 ret.push(k1);
19 }
20 }
21 }
22 } else {
23 for (k2, v2) in mmp2 {
24 let v1 = mmp1.get(&k2);
25 if v1.is_some() {
26 for _ in 0..**[v1.unwrap(), &v2].iter().min().unwrap() {
27 ret.push(k2);
28 }
29 }
30 }
31 }
32 ret
33}
34
35fn main() {
36 println!("{:?}", intersect(vec![1,2,2,1], vec![2,2]));

Callers

nothing calls this directly

Calls 2

getMethod · 0.80
pushMethod · 0.45

Tested by

no test coverage detected