# Leetcode no. 350

114人阅读 评论(0)

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.

• 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?

public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer, Integer> map= new HashMap<>();
for (int ele: nums1) {
if (map.containsKey(ele)) map.put(ele, map.get(ele)+1);
else map.put(ele, 1);
}
for (int ele: nums2) {
if (map.containsKey(ele) && map.get(ele)>0){
map.put(ele, map.get(ele)-1);
}
}
int[] res= new int[list.size()];
int i=0;
Iterator it= list.iterator();
while (it.hasNext()){
res[i++]=(Integer) it.next();
}
return res;
}
}

0
0

个人资料
• 访问：15188次
• 积分：1239
• 等级：
• 排名：千里之外
• 原创：111篇
• 转载：4篇
• 译文：0篇
• 评论：0条
文章分类