0350. Intersection of Two Arrays II (E)

Intersection of Two Arrays II (E)

题目

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:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • 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?

题意

取两数组的交集,包含所有重复元素

思路

普通做法直接用HashMap处理即可。

排序情况下用类似于归并排序的方法处理。


代码实现

Java

Hash

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List list = new ArrayList<>();
        Map record = new HashMap<>();
        for (int num : nums1) {
            record.putIfAbsent(num, 0);
            record.put(num, record.get(num) + 1);
        }

        for (int num : nums2) {
            if (record.containsKey(num) && record.get(num) > 0) {
                list.add(num);
                record.put(num, record.get(num) - 1);
            }
        }

        int[] res = new int[list.size()];
        int i = 0;
        for (int num : list) {
            res[i++] = num;
        }

        return res;
    }
}

排序

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        List list = new ArrayList<>();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int p1 = 0, p2 = 0;
        while (p1 < nums1.length && p2 < nums2.length) {
            if (nums1[p1] > nums2[p2]) {
                p2++;
            } else if (nums1[p1] < nums2[p2]) {
                p1++;
            } else {
                list.add(nums1[p1]);
                p1++;
                p2++;
            }
        }

        int[] res = new int[list.size()];
        int i = 0;
        for (int num : list) {
            res[i++] = num;
        }

        return res;
    }
}

你可能感兴趣的:(0350. Intersection of Two Arrays II (E))