您的位置:首页 > 其它

(Collection)350. Intersection of Two Arrays II

2016-06-25 15:07 260 查看
/* 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.  */

public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map=new HashMap();
List<Integer> list=new ArrayList();
for(int num : nums1){
map.put(num,map.getOrDefault(num,0)+1);
}
int count=0;
for(int num : nums2){
if(map.containsKey(num) && map.get(num)>0){
list.add(num);
map.put(num,map.get(num)-1);
}
}
int[] res=new int[list.size()];
for(int i=0;i<list.size();i++){
res[i]=list.get(i);
}
return res;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: