349. 两个数组的交集

题目描述

给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。

解题思路

#![allow(unused)]

fn main() {
struct Solution {}

impl Solution {
    pub fn intersection(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
        use std::collections::HashSet;
        let mut set1 = HashSet::new();
        let mut set2 = HashSet::new();
        for i in nums1 {
            set1.insert(i);
        }
        for i in nums2 {
            set2.insert(i);
        }
        set1.intersection(&set2).copied().collect()
    }
}

}

学习感想

优雅

#![allow(unused)]
fn main() {
struct Solution {}
use std::iter::FromIterator;
impl Solution {
    pub fn intersection(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
        use std::collections::HashSet;
        let set1: HashSet<i32> = HashSet::from_iter(nums1);
        let set2: HashSet<i32> = HashSet::from_iter(nums2);
        // set1.intersection(&set2).map(|&x| x).collect()
        set1.intersection(&set2).copied().collect()
    }
}

}