题目:
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.
思路:
把nums1中的元素,放到一个map中key为nums1中的值,values是对应nums1中该值出现的次数。
把nums2中的元素,放到另一个map中key为nums2中的值,values是对应nums2中该值出现的次数。
使用一个list存储结果(原因是不知道结果的大小,可以任意添加元素)
依次遍历存储nums1中元素的map的key值获取对应key值的values。与存储map2中对应的key的values对比。选取values值小的元素n,向list中添加n此key值。
具体代码如下:
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int len1 = nums1.length;
int len2 = nums2.length;
if(len1 == 0 || len2 == 0){
return new int[0];
}
Map<Integer,Integer> map1 = new HashMap();
Map<Integer,Integer> map2 = new HashMap();
for(int i : nums1){
map1.put(i, map1.getOrDefault(i, 0)+1);
}
// System.out.println("map1:" + map1.toString());
for(int i : nums2){
map2.put(i, map2.getOrDefault(i, 0)+1);
}
// System.out.println("map2:" + map2.toString());
List<Integer> list = new ArrayList();
for(int j : map1.keySet()){
if(map2.containsKey(j)){
int l = map1.get(j)>map2.get(j)?map2.get(j):map1.get(j);
for(int ll = 0; ll < l; ll++){
list.add(j);
}
}
}
int resultLen = list.size();
int[] result = new int[resultLen];
int n = 0;
for(int jj: list){
result[n] = jj;
n++;
}
return result;
}
}