LeetCode 题解工作台

找出两数组的不同

给你两个下标从 0 开始的整数数组 nums1 和 nums2 ,请你返回一个长度为 2 的列表 answer ,其中: answer[0] 是 nums1 中所有 不 存在于 nums2 中的 不同 整数组成的列表。 answer[1] 是 nums2 中所有 不 存在于 nums1 中的 不同 …

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们定义两个哈希表 和 分别存储数组 和 中的元素。然后遍历 中的每个元素,如果该元素不在 中,那么将其加入到答案的第一个列表中。同理,遍历 中的每个元素,如果该元素不在 中,那么将其加入到答案的第二个列表中。 时间复杂度 ,空间复杂度 。其中 是数组的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个下标从 0 开始的整数数组 nums1nums2 ,请你返回一个长度为 2 的列表 answer ,其中:

  • answer[0]nums1 中所有存在于 nums2 中的 不同 整数组成的列表。
  • answer[1]nums2 中所有存在于 nums1 中的 不同 整数组成的列表。

注意:列表中的整数可以按 任意 顺序返回。

 

示例 1:

输入:nums1 = [1,2,3], nums2 = [2,4,6]
输出:[[1,3],[4,6]]
解释:
对于 nums1 ,nums1[1] = 2 出现在 nums2 中下标 0 处,然而 nums1[0] = 1 和 nums1[2] = 3 没有出现在 nums2 中。因此,answer[0] = [1,3]。
对于 nums2 ,nums2[0] = 2 出现在 nums1 中下标 1 处,然而 nums2[1] = 4 和 nums2[2] = 6 没有出现在 nums1 中。因此,answer[1] = [4,6]。

示例 2:

输入:nums1 = [1,2,3,3], nums2 = [1,1,2,2]
输出:[[3],[]]
解释:
对于 nums1 ,nums1[2] 和 nums1[3] 没有出现在 nums2 中。由于 nums1[2] == nums1[3] ,二者的值只需要在 answer[0] 中出现一次,故 answer[0] = [3]。
nums2 中的每个整数都在 nums1 中出现,因此,answer[1] = [] 。 

 

提示:

  • 1 <= nums1.length, nums2.length <= 1000
  • -1000 <= nums1[i], nums2[i] <= 1000
lightbulb

解题思路

方法一:哈希表

我们定义两个哈希表 s1s1s2s2 分别存储数组 nums1nums1nums2nums2 中的元素。然后遍历 s1s1 中的每个元素,如果该元素不在 s2s2 中,那么将其加入到答案的第一个列表中。同理,遍历 s2s2 中的每个元素,如果该元素不在 s1s1 中,那么将其加入到答案的第二个列表中。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是数组的长度。

1
2
3
4
5
class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        s1, s2 = set(nums1), set(nums2)
        return [list(s1 - s2), list(s2 - s1)]
speed

复杂度分析

指标
时间O(N + M)
空间O(N + M)
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for a candidate who can efficiently use hash tables to optimize lookup times.

  • question_mark

    Ensure the candidate handles duplicate values properly and avoids unnecessary extra work.

  • question_mark

    Check if the candidate can explain how they minimize time complexity with this approach.

warning

常见陷阱

外企场景
  • error

    Forgetting to handle duplicates correctly can result in incorrect output.

  • error

    Not using a hash table or performing inefficient lookups can lead to slower solutions.

  • error

    Overcomplicating the solution by trying to sort or use nested loops unnecessarily.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider variations where arrays may contain negative numbers or zeros.

  • arrow_right_alt

    Challenge the candidate with larger arrays to test the performance of the solution.

  • arrow_right_alt

    Test the solution on edge cases, such as when both arrays are empty or have only one element.

help

常见问题

外企场景

找出两数组的不同题解:数组·哈希·扫描 | LeetCode #2215 简单