当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.350.Intersection of Two Arrays II 两数组的交集2

LeetCode.350.Intersection of Two Arrays II 两数组的交集2

题目描述

350 Intersection of Two Arrays II
https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  1. What if the given array is already sorted? How would you optimize your algorithm?
  2. What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
  3. What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

解题过程


LeetCode.349.Intersection of Two Arrays 两数组的交集
题不同的是,349题要求的是两数组交集的唯一值,此题要求列出交集中所有重复的。
349 题使用集合 Set 即可, 此题需要使用 Map 记下每个元素出现的次数。

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

private static class SolutionV2020 {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (null == nums1 || null == nums2) {
            return null;
        }
        // 数n -> 出现的次数
        Map<Integer, Integer> map = new HashMap<>();
        for (int n : nums1) {
            map.put(n, map.getOrDefault(n, 0) + 1);
        }
        List<Integer> resList = new ArrayList<>();
        for (int n : nums2) {
            if (map.containsKey(n)) {
                int v = map.get(n);
                if (v > 0) {
                    resList.add(n);
                    map.put(n, v - 1);
                }
            }
        }
        return resList.stream().mapToInt(Integer::intValue).toArray();
    }
}

GitHub代码

algorithms/leetcode/leetcode/_350_IntersectionOfTwoArrays2.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_350_IntersectionOfTwoArrays2.java


上一篇 LeetCode.303.Range Sum Query Immutable 不变数组的范围和

下一篇 LeetCode.392.Is Subsequence 判断是否子序列

阅读
评论
340
阅读预计1分钟
创建日期 2020-02-08
修改日期 2020-02-08
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论