leetcode 2215. Find the Difference of Two Arrays(找出2个数组的不同)

该代码实现了一个方法,用于找出两个给定的整数数组nums1和nums2之间的差异元素。它使用了两个boolean数组bn1和bn2,分别标记nums1和nums2中元素的出现情况。然后遍历这两个布尔数组,将只出现在nums1中的元素添加到列表l1,只出现在nums2中的元素添加到列表l2。最后,将l1和l2放入结果列表res并返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述

两个数组nums1 和 nums2.
要找出nums1中有而nums2中没有的元素,放在list[0].
nums2中有而nums1中没有的元素,放在list[1].
最后返回list.

思路:

因为nums1和nums2的元素有值的限制,在-1000 ~ 1000之间。
可以定义2个长度为2000的boolean数组,记录nums1和nums2的每个数字是否出现。
最后比较2个boolean数组即可。
数组下标就是元素的值。

public List<List<Integer>> findDifference(int[] nums1, int[] nums2) {
    boolean[] bn1 = new boolean[2001];
    boolean[] bn2 = new boolean[2001];

    int n1 = nums1.length;
    int n2 = nums2.length;
    int i1 = 0;
    int i2 = 0;

    List<Integer> l1 = new ArrayList<>();
    List<Integer> l2 = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();

    while(i1 < n1 && i2 < n2) {
        bn1[nums1[i1]+1000] = true;
        bn2[nums2[i2]+1000] = true;
        i1 ++;
        i2 ++;
    }
    while(i1 < n1) {bn1[nums1[i1]+1000] = true; i1++;}
    while(i2 < n2) {bn2[nums2[i2]+1000] = true; i2++;}

    for(int i = 0; i < 2001; i++){
        if(bn1[i] && !bn2[i]) l1.add(i-1000);
        if(!bn1[i] && bn2[i]) l2.add(i-1000);
    }

    res.add(l1);
    res.add(l2);
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值