【刷题打卡】350. 两个数组的交集 II

56 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第12天,点击查看活动详情

一、题目描述:

350. 两个数组的交集 II - 力扣(LeetCode) (leetcode-cn.com)

给你两个整数数组 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 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?

二、思路分析:

本题提示使用双指针

使用index1、index2循环两个数组,如果相等就将元素赋值给intersaction数组
其中较小的元素右移,从而保证不缺失元素的遍历;
因为在定义的时候数组的长度是min(nums1,nums2),所以有可能相同元素不足此长度,返回时会出现多0的情况
所以使用sum记录相等元素的长度,最后将intersaction的前sum个元素赋值给该数组即可

三、AC 代码:

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int sum = 0;  // 记录相同的元素
        int j = 0;
        int length1 = nums1.length, length2 = nums2.length;
        int[] intersection = new int[Math.min(length1, length2)];
        int index1 = 0, index2 = 0, index = 0;
   // -------------------    寻找相同元素 ----------------------------
        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 ++ ;
                sum++;
            }
        }
        int[] a = new int [sum];
        index1 = 0;
        index2 = 0;
         index = 0;
  // -----------------   将含多0数组赋值给新数组 *---------------------
                while(index1 <length1 && index2 < length2){
            if(nums1[index1] < nums2[index2]){
                index1 ++;
            }
            else if(nums1[index1] > nums2[index2])
            index2 ++;
            else{
                intersection[index++] = nums1[index1];
                a[j] = nums1[index1];
                index1 ++ ;
                index2 ++ ;
                j++;
            }
        }
        return a;
    }
}

四、参考:

350. 两个数组的交集 II - 两个数组的交集 II - 力扣(LeetCode)