2032. Two Out of Three

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:
- 3, in all three arrays.
- 2, in nums1 and nums2.

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:
- 2, in nums2 and nums3.
- 3, in nums1 and nums2.
- 1, in nums1 and nums3.

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

2032. Two Out of Three
struct Solution;

use std::collections::HashSet;

impl Solution {
    fn two_out_of_three(nums1: Vec<i32>, nums2: Vec<i32>, nums3: Vec<i32>) -> Vec<i32> {
        let s1: HashSet<i32> = nums1.into_iter().collect();
        let s2: HashSet<i32> = nums2.into_iter().collect();
        let s3: HashSet<i32> = nums3.into_iter().collect();
        let mut res: HashSet<i32> = HashSet::new();
        for &x in s1.intersection(&s2) {
            res.insert(x);
        }
        for &x in s2.intersection(&s3) {
            res.insert(x);
        }
        for &x in s3.intersection(&s1) {
            res.insert(x);
        }
        res.into_iter().collect()
    }
}

#[test]
fn test() {
    let nums1 = vec![1, 1, 3, 2];
    let nums2 = vec![2, 3];
    let nums3 = vec![3];
    let mut res = vec![3, 2];
    let mut ans = Solution::two_out_of_three(nums1, nums2, nums3);
    res.sort_unstable();
    ans.sort_unstable();

    assert_eq!(res, ans);
    let nums1 = vec![3, 1];
    let nums2 = vec![2, 3];
    let nums3 = vec![1, 2];
    let mut res = vec![2, 3, 1];
    let mut ans = Solution::two_out_of_three(nums1, nums2, nums3);
    res.sort_unstable();
    ans.sort_unstable();
    assert_eq!(res, ans);

    let nums1 = vec![1, 2, 2];
    let nums2 = vec![4, 3, 3];
    let nums3 = vec![5];
    let mut res: Vec<i32> = vec![];
    let mut ans = Solution::two_out_of_three(nums1, nums2, nums3);
    res.sort_unstable();
    ans.sort_unstable();
    assert_eq!(res, ans);
}