carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2032: Two Out of Three #326

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given three integer arrays nums1, nums2, and nums3, return a distinct array containing all the values that are present in at least two out of the three arrays. You may return the values in any order.

Example 1:

Input: nums1 = [1,1,3,2], nums2 = [2,3], nums3 = [3] Output: [3,2] Explanation: The values that are present in at least two arrays are:

Example 2:

Input: nums1 = [3,1], nums2 = [2,3], nums3 = [1,2] Output: [2,3,1] Explanation: The values that are present in at least two arrays are:

Example 3:

Input: nums1 = [1,2,2], nums2 = [4,3,3], nums3 = [5] Output: [] Explanation: No value is present in at least two arrays.

Constraints:

1 <= nums1.length, nums2.length, nums3.length <= 100 1 <= nums1[i], nums2[j], nums3[k] <= 100

carloscn commented 1 year ago

Analysis

use std::collections::HashSet;

fn check_intersection(a:&Vec<i32>, b:&Vec<i32>) -> Vec<i32>
{
    let mut ret:Vec<i32> = vec![];

    if a.len() < 1 || b.len() < 1 {
        return ret;
    }

    let set1:HashSet<_> = a.into_iter().collect();
    let set2:HashSet<_> = b.into_iter().collect();
    let intersection:HashSet<_> = set1.intersection(&set2).collect();

    ret = intersection.into_iter().map(|x| **x).collect();

    return ret;
}

pub fn two_out_of_three(nums1: Vec<i32>, nums2: Vec<i32>, nums3: Vec<i32>) -> Vec<i32>
{
    if nums1.len() < 1 && nums2.len() < 1 && nums3.len() < 1 {
        return vec![];
    }

    let mut ret:Vec<i32> = vec![];

    ret.append(check_intersection(&nums1, &nums2).as_mut());
    ret.append(check_intersection(&nums1, &nums3).as_mut());
    ret.append(check_intersection(&nums2, &nums3).as_mut());

    ret.sort();
    ret.dedup();

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168405 https://github.com/carloscn/structstudy/commit/ffa8e9165a64f343c775dd67c493b147ab48c133