题目描述:
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.
简单题,不多说了,一个hashmap存nums1的状态, 另一个存储nums2 的, 遍历找到都存在的key值返回
代码:
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int[]insct;
ArrayList<Integer>tempList=new ArrayList<Integer>();
HashMap<Integer,Integer>map1=new HashMap<Integer,Integer>(),map2=new HashMap<Integer,Integer>(),map_temp,map_temp2;
for(int n:nums1){
if(map1.containsKey(n)){
map1.put(n, map1.get(n)+1);
}
else
map1.put(n,1);
}
for(int n:nums2){
if(map2.containsKey(n)){
map2.put(n, map2.get(n)+1);
}
else
map2.put(n,1);
}
if(map1.size()>map2.size()){
map_temp=map2;
map_temp2=map1;
}
else
{
map_temp=map1;
map_temp2=map2;
}
int times;
for(int n:map_temp.keySet()){
if(!map_temp2.containsKey(n))continue;
// System.out.println(map_temp2.containsKey(n)+" "+n);
times=Math.min(map_temp.get(n),map_temp2.get(n));
for(int i=0;i<times;i++)
tempList.add(n);
}
insct=new int[tempList.size()];
for(int i=0;i<tempList.size();i++){
insct[i]=tempList.get(i);
}
return insct;
}
}