rs: add «349. Intersection of Two Arrays»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-03-10 22:23:40 +01:00
parent 46088cf458
commit dbd0883d68
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,17 @@
use std::collections::HashSet;
impl Solution {
pub fn intersection(mut nums1: Vec<i32>, mut nums2: Vec<i32>) -> Vec<i32> {
// if nums1 is bigger, swap them
if nums1.len() > nums2.len() {
return Self::intersection(nums2, nums1);
}
let nums: HashSet<i32> = nums1.into_iter().collect();
nums2.sort_unstable();
nums.into_iter()
.filter(|x| nums2.binary_search(x).is_ok())
.collect()
}
}