2248. Intersection of Multiple Arrays Easy
1/**
2 * [2248] Intersection of Multiple Arrays
3 *
4 * Given a 2D integer array nums where nums[i] is a non-empty array of distinct positive integers, return the list of integers that are present in each array of nums sorted in ascending order.
5 *
6 * Example 1:
7 *
8 * Input: nums = [[<u>3</u>,1,2,<u>4</u>,5],[1,2,<u>3</u>,<u>4</u>],[<u>3</u>,<u>4</u>,5,6]]
9 * Output: [3,4]
10 * Explanation:
11 * The only integers present in each of nums[0] = [<u>3</u>,1,2,<u>4</u>,5], nums[1] = [1,2,<u>3</u>,<u>4</u>], and nums[2] = [<u>3</u>,<u>4</u>,5,6] are 3 and 4, so we return [3,4].
12 * Example 2:
13 *
14 * Input: nums = [[1,2,3],[4,5,6]]
15 * Output: []
16 * Explanation:
17 * There does not exist any integer present both in nums[0] and nums[1], so we return an empty list [].
18 *
19 *
20 * Constraints:
21 *
22 * 1 <= nums.length <= 1000
23 * 1 <= sum(nums[i].length) <= 1000
24 * 1 <= nums[i][j] <= 1000
25 * All the values of nums[i] are unique.
26 *
27 */
28pub struct Solution {}
29use std::collections::HashSet;
30
31// problem: https://leetcode.com/problems/intersection-of-multiple-arrays/
32// discuss: https://leetcode.com/problems/intersection-of-multiple-arrays/discuss/?currentPage=1&orderBy=most_votes&query=
33
34// submission codes start here
35
36impl Solution {
37 pub fn intersection(nums: Vec<Vec<i32>>) -> Vec<i32> {
38 let set: HashSet<i32> = nums[0].iter().copied().collect();
39 let x = nums.iter().fold(set, |a, e|
40 a.intersection(&e.iter().copied().collect::<HashSet<i32>>()).map(|x| *x).collect());
41
42 let mut x: Vec<i32> = x.iter().copied().collect();
43 x.sort();
44 x
45 }
46}
47
48// submission codes end
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn test_2248() {
56 assert_eq!(
57 Solution::intersection(vec![vec![1, 2, 3], vec![6, 2, 3]]),
58 vec![2, 3]
59 );
60 }
61}
62
Back
© 2025 bowen.ge All Rights Reserved.