leetcode:找出两数组不同

找出两数组的不同

easy

给你两个下标从 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 没有出现在 nums2 中。因此,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] = [] 。 

哈希集合

python 复制代码
class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        nums1 = set(nums1)
        nums2 = set(nums2)
        same_num = nums1 & nums2
        return [list(nums1 - same_num), list(nums2 - same_num)]

递归

python 复制代码
class Solution(object):
    def findDifference(self, nums1, nums2):
        se1, se2 = set(nums1), set(nums2)  # 使用集合去重
        answer = [list(se1 - se2), list(se2 - se1)]
        return answer

字典(效率低)

python 复制代码
class Solution:
    def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]:
        dict1 = {}
        dict2 = {}
        for i, n in enumerate(nums1):
            if n not in nums2:
                dict1[n] = i

        for i, n in enumerate(nums2):
            if n not in nums1:
                dict2[n] = i
            
        return [list(dict1.keys()), list(dict2.keys())]
相关推荐
2401_8582861113 分钟前
125.【C语言】数据结构之归并排序递归解法
c语言·开发语言·数据结构·算法·排序算法·归并排序
guygg881 小时前
基于matlab的FIR滤波器
开发语言·算法·matlab
ysh98881 小时前
PP-OCR:一款实用的超轻量级OCR系统
算法
遇雪长安2 小时前
差分定位技术:原理、分类与应用场景
算法·分类·数据挖掘·rtk·差分定位
天真小巫2 小时前
2025.7.6总结
职场和发展
数通Dinner2 小时前
RSTP 拓扑收敛机制
网络·网络协议·tcp/ip·算法·信息与通信
张人玉3 小时前
C# 常量与变量
java·算法·c#
weixin_446122464 小时前
LinkedList剖析
算法
百年孤独_5 小时前
LeetCode 算法题解:链表与二叉树相关问题 打打卡
算法·leetcode·链表
我爱C编程6 小时前
基于拓扑结构检测的LDPC稀疏校验矩阵高阶环检测算法matlab仿真
算法·matlab·矩阵·ldpc·环检测