LeetCode 题解工作台

找到两个数组中的公共元素

给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,它们分别含有 n 和 m 个元素。请你计算以下两个数值: answer1 :使得 nums1[i] 在 nums2 中出现的下标 i 的数量。 answer2 :使得 nums2[i] 在 nums1 中出现的下标 i 的数量。 返回…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以用两个哈希表或数组 和 分别记录两个数组中出现的元素。 接下来,我们创建一个长度为 的数组 ,其中 表示 中出现在 中的元素个数, 表示 中出现在 中的元素个数。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,它们分别含有 n 和 m 个元素。请你计算以下两个数值:

  • answer1:使得 nums1[i] 在 nums2 中出现的下标 i 的数量。
  • answer2:使得 nums2[i] 在 nums1 中出现的下标 i 的数量。

返回 [answer1, answer2]

 

示例 1:

输入:nums1 = [2,3,2], nums2 = [1,2]

输出:[2,1]

解释:

示例 2:

输入:nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]

输出:[3,4]

解释:

nums1 中下标在 1,2,3 的元素在 nums2 中也存在。所以 answer1 为 3。

nums2 中下标在 0,1,3,4 的元素在 nums1 中也存在。所以 answer2 为 4。

示例 3:

输入:nums1 = [3,4,2,3], nums2 = [1,5]

输出:[0,0]

解释:

nums1 和 nums2 中没有相同的数字,所以答案是 [0,0]。

 

提示:

  • n == nums1.length
  • m == nums2.length
  • 1 <= n, m <= 100
  • 1 <= nums1[i], nums2[i] <= 100
lightbulb

解题思路

方法一:哈希表或数组

我们可以用两个哈希表或数组 s1s1s2s2 分别记录两个数组中出现的元素。

接下来,我们创建一个长度为 22 的数组 ansans,其中 ans[0]ans[0] 表示 nums1nums1 中出现在 s2s2 中的元素个数,ans[1]ans[1] 表示 nums2nums2 中出现在 s1s1 中的元素个数。

然后,我们遍历数组 nums1nums1 中的每个元素 xx,如果 xxs2s2 中出现过,则将 ans[0]ans[0] 加一。接着,我们遍历数组 nums2nums2 中的每个元素 xx,如果 xxs1s1 中出现过,则将 ans[1]ans[1] 加一。

最后,我们返回数组 ansans 即可。

时间复杂度 O(n+m)O(n + m),空间复杂度 O(n+m)O(n + m)。其中 nnmm 分别是数组 nums1nums1nums2nums2 的长度。

1
2
3
4
5
class Solution:
    def findIntersectionValues(self, nums1: List[int], nums2: List[int]) -> List[int]:
        s1, s2 = set(nums1), set(nums2)
        return [sum(x in s2 for x in nums1), sum(x in s1 for x in nums2)]
speed

复杂度分析

指标
时间complexity is O(n + m) using hash sets for both arrays. Space complexity is O(n + m) for storing hash sets. Brute force is O(n*m) time and O(1) space, only suitable for small arrays.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate considers both directions of counting elements.

  • question_mark

    Notice if duplicates are counted separately or ignored.

  • question_mark

    Evaluate if the candidate uses hash sets for faster lookup instead of nested loops.

warning

常见陷阱

外企场景
  • error

    Counting duplicates incorrectly or only once instead of per occurrence.

  • error

    Ignoring one direction of counting, giving an incomplete answer.

  • error

    Using nested loops on larger inputs, leading to inefficient O(n*m) performance.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the actual common elements list instead of counts, preserving order from one array.

  • arrow_right_alt

    Handle more than two arrays, finding elements common to all arrays.

  • arrow_right_alt

    Compute intersection using sorted arrays and two-pointer technique instead of hash sets.

help

常见问题

外企场景

找到两个数组中的公共元素题解:数组·哈希·扫描 | LeetCode #2956 简单