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?
package leetcode;
import java.util.ArrayList;
import java.util.HashMap;
public class Intersection_of_Two_Arrays_II_350 {
public int[] intersect(int[] nums1, int[] nums2) {
ArrayList<Integer> intersect=new ArrayList<Integer>();
HashMap<Integer, Integer> map=new HashMap<Integer, Integer>();
for(int i=0;i<nums1.length;i++){
int count=map.getOrDefault(nums1[i], 0);
count++;
map.put(nums1[i], count);
}
for(int i=0;i<nums2.length;i++){
int count=map.getOrDefault(nums2[i], 0);
if(count==0){
continue;
}
else{
count--;
intersect.add(nums2[i]);
map.put(nums2[i], count);
}
}
int[] result=new int[intersect.size()];
for(int i=0;i<intersect.size();i++){
result[i]=intersect.get(i);
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Intersection_of_Two_Arrays_II_350 i=new Intersection_of_Two_Arrays_II_350();
int[] nums1=new int[]{1,2,2,1};
int[] nums2=new int[]{2,2};
int[] result=i.intersect(nums1, nums2);
for(int j=0;j<result.length;j++){
System.out.print(result[j]+" ");
}
}
}
至于后续的这个问题,大神也想出了解决办法:
- 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?
2. 如果nums1和nums2都太大了以至于不能被内存所容纳,那么将它们分别排序 (external sort),然后每次分别从两个数组中各拿出一个元素放入内存中,来比较取交集。
有大神继续讨论:谢谢你的解法,但是我觉得2不太可行,因为如果你一次仅仅从磁盘中取2个元素,而磁盘读取十分耗时,所以这个过程将花费很多时间。原则上我们应该在运行时最小化磁盘读取次数。
一个可取的改进方案是:我们先使用外部排序将它们分别排序,如果内存是4G,那么我们就分别从这两个数组中取出2G放入内存,使用 2 pointer 方法来找交集,这部分完成后,再分别读2G入内存,重复直到磁盘上再也没有更多数据了。
另一个大神说:在面试中这样的问题是考验答题者是否了解一些数据工程技术。我从一个数据工程师的角度,觉得有三种思路来解决这个问题:
1. 将这2个数组存储在分布式系统中,然后使用MapReduce技术来解决问题
2. 分块处理这2个数组,(块fit内存),然后每一次处理一个块数据。
3. 流式处理数组,然后核查。
对于external sort的技术,这篇文章里有介绍:http://faculty.simpson.edu/lydia.sinapova/www/cmsc250/LN250_Weiss/L17-ExternalSortEX2.htm