原题:
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.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1’s size is small compared to nums2’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?
题意:
求两个数组的交集(包括重复出现的元素)。
思路:
1.遍历数组nums1,将其中的元素放入HashMap<Integer,Integer>
中进行统计;
2.新建ArrayList作为存储交集的元素(可重复元素);
3.遍历数组nums2,如果元素num2在map中出现过,则将其加入到list中,并将其对应的值-1;
4.将list转为数组返回即可。
代码:
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int num1:nums1){
if(!map.containsKey(num1)){
map.put(num1,1);
}else{
map.put(num1,map.get(num1) + 1);
}
}
List<Integer> list = new ArrayList<Integer>();
for(int num2:nums2){
if(map.containsKey(num2) && map.get(num2) > 0){
list.add(num2);
map.put(num2,map.get(num2) - 1);
}
}
int[] res = new int[list.size()];
for(int i = 0;i < list.size();i++){
res[i] = list.get(i);
}
return res;
}
}