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]
.
题目:升级版找两个数组的交集,初级版只对交集元素有要求,这个升级版还对元素的数量有要求
思路:偷懒一下,用Intersection of Two Arrays 的算法改动一下,看了下讨论,基本也是用hash,欢迎交流不同解法
public int[] intersect(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
if(len1==0 || len2==0){
return new int[0];
}
HashMap<Integer,Integer> map1 = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> map2 = new HashMap<Integer,Integer>();
for(int i = 0;i<len1;i++){
Integer temp = map1.get(nums1[i]);
if(temp == null){
map1.put(nums1[i],1);
}else{
map1.put(nums1[i],temp+1);
}
}
for(int i = 0;i<len2;i++){
Integer temp = map2.get(nums2[i]);
if(temp == null){
map2.put(nums2[i],1);
}else{
map2.put(nums2[i],temp+1);
}
}
boolean flag = map1.size()>map2.size();
if(!flag){
HashMap<Integer,Integer> tempMap = map1;
map1 = map2;
map2 = tempMap;
}
List<Integer> resList = new ArrayList<Integer>();
for(Entry e : map1.entrySet()){
Integer key = (Integer)e.getKey();
Integer v1 = (Integer)e.getValue();
if(map2.get(key)!=null){
Integer v2 = map2.get(key);
int n = v1>v2?v2:v1;
for(int i = 0;i<n;i++){
resList.add(key);
}
}
}
int resSize = resList.size();
int res [] = new int[resSize];
for(int i = 0;i<resSize;i++){
res[i] = resList.get(i);
}
return res;
}