Given two arrays, write a function to compute their intersection.
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0)
return new int[0];
HashMap<Integer, Integer> map1 = new HashMap<>();
HashMap<Integer, Integer> map2 = new HashMap<>();
for(int n: nums1) {
if(map1.containsKey(n))
map1.put(n, 1 + map1.get(n));
else
map1.put(n, 1);
}
for(int n: nums2) {
if(map2.containsKey(n))
map2.put(n, 1 + map2.get(n));
else
map2.put(n, 1);
}
List<Integer> list = new ArrayList<Integer>();
for(Integer key: map1.keySet()) {
if(map2.containsKey(key)) {
for(int i = 0; i < Math.min(map1.get(key), map2.get(key)); i++)
list.add(key);
}
}
int[] res = new int[list.size()];
for(int i = 0; i < res.length; i++)
res[i] = list.get(i);
return res;
}
}
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- Two pointers
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- 交换nums1和nums2在代码中的位置
- 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?
- 分批load