[LeetCode] Intersection of Two Arrays II
Posted 楚兴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Intersection of Two Arrays II相关的知识,希望对你有一定的参考价值。
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
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 num2’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?
解题思路
两个map分别存储两个数组的元素出现次数,然后以最少出现次数决定是否出现在结果数组中以及出现在结果数组中的次数。
实现代码
// Runtime: 13 ms
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map1 = new HashMap<Integer, Integer>();
for (int num : nums1) {
if (map1.containsKey(num)) {
map1.put(num, map1.get(num) + 1);
} else {
map1.put(num, 1);
}
}
Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();
for (int num : nums2) {
if (map2.containsKey(num)) {
map2.put(num, map2.get(num) + 1);
} else {
map2.put(num, 1);
}
}
List<Integer> list = new ArrayList<Integer>();
for (Map.Entry<Integer, Integer> entry : map1.entrySet()) {
int times = entry.getValue();
if (map2.containsKey(entry.getKey())) {
times = Math.min(times, map2.get(entry.getKey()));
} else {
times = 0;
}
for (int i = 0; i < times; i++) {
list.add(entry.getKey());
}
}
int[] res = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}
以上是关于[LeetCode] Intersection of Two Arrays II的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 160. Intersection of Two Linked Lists
349. Intersection of Two Arrays
[LeetCode] 349 Intersection of Two Arrays & 350 Intersection of Two Arrays II
LeetCode:Intersection of Two Arrays