LeetCode 数据结构与算法之两个数组的交集 II

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第12天,点击查看活动详情

题目

350. 两个数组的交集 II

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

示例 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
复制代码

进阶: 如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小,哪种方法更优?
如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

题解

解题分析

解题思路

  1. 思路:对两个数组进行排序,然后使用双指针的方式获取到两个数组的交集
  2. 首先排序,然后用双指针遍历两个数组
  3. 初始时,两个指针分别指向数组的头部。每次比较两个指针中的两个数字 :
    • 如果两个数字不相等,则将指向较小数字的指针右移一位,
    • 如果两个数字相等,将该数字添加到答案,并且将两个指针都右移一位。
    • 当至少有一个指针超出数组范围时,遍历结束。

复杂度

时间复杂度 O(N)
空间复杂度 O(|Σ|)

解题代码

题解代码如下(代码中有详细的注释说明):

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        // 1. 排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);

        int length1 = nums1.length, length2 = nums2.length;
        int[] intersection = new int[Math.min(length1, length2)];
        int index1 = 0, index2 = 0, index = 0;
        // 2. 两个指针 index1, index2
        while(index1 < length1 && index2 < length2) {
            if (nums1[index1] < nums2[index2]) {
                index1++;
            } else if (nums1[index1] > nums2[index2]) {
                index2++;   
            } else {
                intersection[index] = nums1[index1];
                index1++;
                index2++;
                index++;
            }
        }
        return Arrays.copyOfRange(intersection, 0, index);
    }
}
复制代码

提交后反馈结果(由于该题目没有进行优化,性能一般):

image.png

参考信息

猜你喜欢

转载自juejin.im/post/7085707726776434695
今日推荐