# LeetCode 350. 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 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? Subscribe to see which companies asked this question.

# 代码

```public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums1.length; ++i) {
if (map.containsKey(nums1[i]))
map.put(nums1[i], map.get(nums1[i]) + 1);
else
map.put(nums1[i], 1);
}

List<Integer> results = new ArrayList<Integer>();

for (int i = 0; i < nums2.length; ++i)
if (map.containsKey(nums2[i]) &&
map.get(nums2[i]) > 0) {
map.put(nums2[i], map.get(nums2[i]) - 1);
}

int result[] = new int[results.size()];
for(int i = 0; i < results.size(); ++i)
result[i] = results.get(i);

return result;
}
}```

381 篇文章35 人订阅

0 条评论

## 相关文章

854

1695

784

1102

1061

### tensorflow编程: Variables

tf.moving_average_variables tf.global_variables_initializer tf.local_variabl...

1381

### Java Integer 类 解读

Integer 类是Java中最常用的类型，它是原生类型 int 的包装类。在开发中我们基本可以将两者等价。但是，最近在开发中遇到一个 == 与 equals ...

2503

742

### PHP数据结构（十二） ——静态查找表​

PHP数据结构（十二）——静态查找表 （原创内容，转载请注明来源，谢谢） 一、概念 1、查找表：由同一类型数据元素构成的集合。 ...

3687

### 5-Java基础语法-流程控制之循环结构

while循环;do-while循环;for循环;循环嵌套;break语句;continue语句

1911