LeetCode 题解工作台

多个数组求交集

给你一个二维整数数组 nums ,其中 nums[i] 是由 不同 正整数组成的一个非空数组,按 升序排列 返回一个数组,数组中的每个元素在 nums 所有数组 中都出现过。 示例 1: 输入: nums = [[ 3 ,1,2, 4 ,5],[1,2, 3 , 4 ],[ 3 , 4 ,5,6]]…

category

4

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

遍历数组 `nums`,对于每个数组 `arr`,统计数组 `arr` 中每个数字出现的次数,然后遍历计数数组,统计出现次数等于数组 `nums` 的长度的数字,即为答案。 时间复杂度 ,空间复杂度 。其中 为数组 `nums` 中数字的总数。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二维整数数组 nums ,其中 nums[i] 是由 不同 正整数组成的一个非空数组,按 升序排列 返回一个数组,数组中的每个元素在 nums 所有数组 中都出现过。

 

示例 1:

输入:nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]]
输出:[3,4]
解释:
nums[0] = [3,1,2,4,5],nums[1] = [1,2,3,4],nums[2] = [3,4,5,6],在 nums 中每个数组中都出现的数字是 3 和 4 ,所以返回 [3,4] 。

示例 2:

输入:nums = [[1,2,3],[4,5,6]]
输出:[]
解释:
不存在同时出现在 nums[0] 和 nums[1] 的整数,所以返回一个空列表 [] 。

 

提示:

  • 1 <= nums.length <= 1000
  • 1 <= sum(nums[i].length) <= 1000
  • 1 <= nums[i][j] <= 1000
  • nums[i] 中的所有值 互不相同
lightbulb

解题思路

方法一:计数

遍历数组 nums,对于每个数组 arr,统计数组 arr 中每个数字出现的次数,然后遍历计数数组,统计出现次数等于数组 nums 的长度的数字,即为答案。

时间复杂度 O(N)O(N),空间复杂度 O(1000)O(1000)。其中 NN 为数组 nums 中数字的总数。

1
2
3
4
5
6
7
8
class Solution:
    def intersection(self, nums: List[List[int]]) -> List[int]:
        cnt = [0] * 1001
        for arr in nums:
            for x in arr:
                cnt[x] += 1
        return [x for x, v in enumerate(cnt) if v == len(nums)]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Strong candidates will use a hash table to efficiently count occurrences and check common elements.

  • question_mark

    Look for solutions that optimize the time complexity using sorting or direct set operations.

  • question_mark

    Candidates should demonstrate an understanding of array scanning and hash table usage.

warning

常见陷阱

外企场景
  • error

    Failing to account for the case where no common elements exist, leading to incorrect results.

  • error

    Not efficiently handling large inputs, causing time or space complexity issues.

  • error

    Misusing sorting or set operations that increase the problem's complexity unnecessarily.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the problem to find common elements that appear in at least half the subarrays.

  • arrow_right_alt

    Alter the problem to return only those common elements that appear more than once in each subarray.

  • arrow_right_alt

    Modify the problem to require returning the common elements in sorted order.

help

常见问题

外企场景

多个数组求交集题解:数组·哈希·扫描 | LeetCode #2248 简单