美文网首页
LeetCode刷题分类之双指针350. 两个数组的交集 II

LeetCode刷题分类之双指针350. 两个数组的交集 II

作者: 逍遥白亦 | 来源:发表于2020-12-29 23:17 被阅读0次

350. 两个数组的交集 II

题目

给定两个数组,编写一个函数来计算它们的交集。

示例 1:

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

示例 2:

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

思路

如果两个数组是有序的,则可以便捷地计算两个数组的交集。

首先对两个数组进行排序,然后使用两个指针遍历两个数组。

初始时,两个指针分别指向两个数组的头部。每次比较两个指针指向的两个数组中的数字,如果两个数字不相等,则将指向较小数字的指针右移一位,如果两个数字相等,将该数字添加到答案,并将两个指针都右移一位。当至少有一个指针超出数组范围时,遍历结束。

代码

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        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;

        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);
    }
}

相关文章

网友评论

      本文标题:LeetCode刷题分类之双指针350. 两个数组的交集 II

      本文链接:https://www.haomeiwen.com/subject/mjccoktx.html