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:
- 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?
解题过程
和
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
页面信息
location:
protocol
: host
: hostname
: origin
: pathname
: href
: document:
referrer
: navigator:
platform
: userAgent
: