LeetCode日记 350.两个数组的交集II

在这里插入图片描述
题目来源:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/

1.思路:先将两个数组排好序,用两个指针s1,s2分别同时遍历两个数组,如果两个指针指向的数相同,就一起后移并将结果存入list中。nums[s1]<nums[s2],那就s1后移;nums[s1]>nums[s2],就s2后移。最后遍历list,将结果集存放到数组中。

时间复杂度:O(m log m+n log n)
空间复杂度:O(min(m,n))

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int len1 = nums1.length,len2 = nums2.length;
        ArrayList<Integer> res = new ArrayList();
        int s1 = 0,s2 = 0;
        while(s1<len1&&s2<len2){
            if(nums1[s1]==nums2[s2]){
                res.add(nums1[s1]);
                s1++;
                s2++;
            }else if(nums1[s1]<nums2[s2]){
                s1++;
            }else{
                s2++;
            }
        }

        int[] ans = new int[res.size()];
        for(int i = 0;i<res.size();i++){
            ans[i] = res.get(i);
        }

        return ans;
    }
}

2.看了官方题解,还可以用hash法
由于同一个数字在两个数组中都可能出现多次,因此需要用哈希表存储每个数字出现的次数。对于一个数字,其在交集中出现的次数等于该数字在两个数组中出现次数的最小值。

首先遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数,然后遍历第二个数组,对于第二个数组中的每个数字,如果在哈希表中存在这个数字,则将该数字添加到答案,并减少哈希表中该数字出现的次数。

为了降低空间复杂度,首先遍历较短的数组并在哈希表中记录每个数字以及对应出现的次数,然后遍历较长的数组得到交集。
在这里插入图片描述

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        HashMap<Integer,Integer> map = new HashMap();
        ArrayList<Integer> res = new ArrayList();
        //遍历短的那个数组,在map中记录出现过的数字及其出现的次数
        for(int num:nums1){
            if(map.containsKey(num)){
                map.put(num,map.get(num)+1);
            }else{
                map.put(num,1);
            }
        }
        //遍历长数组,若长数组中的数字在map中存在,加入结果集,key对应的次数也减少
        for(int num:nums2){
            int count = map.getOrDefault(num,0);
            if (count > 0) {
                res.add(num);
                count--;
            if (count > 0) {
                    map.put(num, count);
                } else {
                    map.remove(num);
                }
            }

        }

        int[] ans = new int[res.size()];
        for(int i = 0;i<res.size();i++){
            ans[i] = res.get(i);
        }
        return ans;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值