From dbd0883d683c24f832350d8d49f82c93b1ee13d4 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 10 Mar 2024 22:23:40 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB349.=20Intersection=20of=20Tw?= =?UTF-8?q?o=20Arrays=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/intersection-of-two-arrays.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 rs/intersection-of-two-arrays.rs diff --git a/rs/intersection-of-two-arrays.rs b/rs/intersection-of-two-arrays.rs new file mode 100644 index 0000000..7b2cc2f --- /dev/null +++ b/rs/intersection-of-two-arrays.rs @@ -0,0 +1,17 @@ +use std::collections::HashSet; + +impl Solution { + pub fn intersection(mut nums1: Vec, mut nums2: Vec) -> Vec { + // if ‹nums1› is bigger, swap them + if nums1.len() > nums2.len() { + return Self::intersection(nums2, nums1); + } + + let nums: HashSet = nums1.into_iter().collect(); + nums2.sort_unstable(); + + nums.into_iter() + .filter(|x| nums2.binary_search(x).is_ok()) + .collect() + } +}