LeetCode题解(Java):350-两个数组的交集 II

350. 两个数组的交集 II

https://leetcode-cn.com/problems/intersection-of-two-arrays-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]

解法一:HashMap

  1. 使用Map统计nums1数字的个数
  2. 遍历nums2,查找当前数字是否在Map中
  3. 若在且出现个数大于0,说明这个数是交集中的一个元素
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length * nums2.length == 0) return new int[]{};
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums1) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        int index = 0;
        for (int i : nums2) {
            if (map.containsKey(i)) {
                int cnt = map.get(i);
                if (cnt > 0) {
                    nums2[index++] = i;
                    map.put(i, cnt - 1);
                }
            }
        }
        return Arrays.copyOf(nums2, index);
    }
}
  • 时间复杂度:O(M + N)
  • 空间复杂度:O(M) 或者 O(N)

解法二:排序+双指针

  1. 分别对nums1、nums2进行排序
  2. 使用指针i,j分别对nums1、nums2遍历
  3. nums[i]==nums[j]时,为一个答案
  4. nums[i] > nums[j]时,j++
  5. nums[i] < nums[j]时,i++
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length * nums2.length == 0) return new int[]{};
        Arrays.sort(nums1); Arrays.sort(nums2);
        int i = 0, j = 0, k = 0;
        int[] ans = new int[nums1.length];
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] == nums2[j]) {
                ans[k++] = nums1[i++];
                j++;
            } else if (nums1[i] < nums2[j]) {
                i++;
            } else {
                j++;
            }
        }
        return Arrays.copyOf(ans, k);
    }
}
  • 时间复杂度:O(MlogM + NlogN)
  • 空间复杂度:O(M) 或者 O(N)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值