LeetCode 350. 两个数组的交集 II(java)

给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。

示例 1:

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
 

提示:

1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/intersection-of-two-arrays-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解:

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        Queue<Integer> queue1 = new LinkedList<>();
        Queue<Integer> queue2 = new LinkedList<>();
        int[] ret = new int[2010];
        for (int i = 0; i < ret.length; i++) {
            ret[i] = -1;
        }
        for (int i:nums1
             ) {
            queue1.offer(i);
        }
        for (int i:nums2
             ) {
            queue2.offer(i);
        }
        int i = 0;
        while (!queue1.isEmpty() && !queue2.isEmpty()) {
            int q1 = queue1.peek();
            int q2 = queue2.peek();
            if (q1 == q2) {
                ret[i++] = q1;
                queue1.poll();
                queue2.poll();
            } else if (q1 < q2) {
                queue1.poll();
            } else {
                queue2.poll();
            }
        }
        int count = 0;
        for (int j = 0; j < ret.length; j++) {
            if (ret[j] == -1) break;
            count++;
        }
        int[] result = new int[count];
        for (int j = 0; j < count; j++) {
            result[j] = ret[j];
        }
        return result;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

喜欢喝雪碧的阿埋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值