Given two arrays, write a function to compute their intersection.
Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to num2'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?
本题的问题与系列中的第一题基本相同,只是需要考虑在intersection中重复的数量。同样利用HashMap记录,不过这次需要记录nums1[]中出现次数,并且在结果的resultMap中记录同时在nums2[]出现的次数。
public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
HashMap<Integer, Integer> resultMap = new HashMap<Integer, Integer>();
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < nums1.length; i++) {
if (!map.containsKey(nums1[i])) {
map.put(nums1[i], 1);
} else {
map.put(nums1[i], map.get(nums1[i]) + 1);
}
}
for (int j = 0; j < nums2.length; j++) {
if (map.containsKey(nums2[j]) && map.get(nums2[j]) > 0) {
map.put(nums2[j], map.get(nums2[j]) - 1);
if (!resultMap.containsKey(nums2[j])) {
resultMap.put(nums2[j], 1);
} else {
resultMap.put(nums2[j], resultMap.get(nums2[j]) + 1);
}
}
}
int sum = 0;
for (Integer e : resultMap.keySet()) {
int count = resultMap.get(e);
sum += count;
for (int i = 0; i < count; i++) {
list.add(e);
}
}
int[] result = new int[sum];
for (int i = 0; i < sum; i++) {
result[i] = (int) list.get(i);
}
return result;
}
}