今日leetcode 349.两个数组的交集

349. 两个数组的交集

给定两个数组 nums1 和 nums2 ,返回 它们的 

交集

 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。

示例 1:

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

示例 2:

输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的

提示:

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

题解:(时间复杂度:O(m + n))

法一:利用哈希表,将数组1内的元素存入哈希表中,而后遍历数组2,找出数组1与数组2的交集,放到新的哈希表中,返回新的哈希表。

class Solution {
    public int[] intersection(int[] nums1,int[] nums2){
        Set<Integer> table1 = new HashSet<>();
        Set<Integer> resTable = new HashSet<>();
        for(int num : nums1){
            table1.add(num);
        }
        for(int num : nums2){
            if(table1.contains(num)){
                resTable.add(num);
            }
        }
        return resTable.stream().mapToInt(x -> x).toArray();
    }
}

法二:排序 + 双指针

先对两数组进行排序,使其按照从小到大的顺序排列,使其顺序与大小相关,方便后续指针移动条件的判别。

条件判别:

当两指针有一个指针遍历完其所遍历的数组结束循环

若指针1所指的数字较大,则指针2指向相较其更大些的数字,即向右移动。

一旦发现两指针指向相同数字,取出这个元素,添加到目标数组(集合)中,指针后移继续判别。

代码实现:

class Solution {
    public int[] intersection(int[] nums1,int[] nums2){
        // 对数组先进行排序
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int index1 = 0;
        int index2 = 0;
        Set<Integer> resTable = new HashSet<>();
        while(index1 < nums1.length && index2 < nums2.length){
            if(nums1[index1] == nums2[index2]){
                resTable.add(nums1[index1]);
                index1++;
                index2++;
            }else if(nums1[index1] > nums2[index2]){
                index2++;
            }else {
                index1++;
            }
        }
        return resTable.stream().mapToInt(x -> x).toArray();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值