349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note:
- Each element in the result must be unique.
- The result can be in any order.
Rust Solution
struct Solution;
use std::collections::HashSet;
impl Solution {
fn intersection(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let h1: HashSet<i32> = nums1.into_iter().collect();
let h2: HashSet<i32> = nums2.into_iter().collect();
let bitand = &h1 & &h2;
bitand.into_iter().collect()
}
}
#[test]
fn test() {
let nums1 = vec![1, 2, 2, 1];
let nums2 = vec![2, 2];
assert_eq!(Solution::intersection(nums1, nums2), vec![2]);
}
Having problems with this solution? Click here to submit an issue on github.