问题链接:https://leetcode.com/problems/intersection-of-two-arrays-ii/
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?
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1==null || nums2==null || nums1.length==0 || nums2.length==0) {
return new int[]{};
}
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
List<Integer> res = new LinkedList<Integer>();
for(int i=0;i<nums1.length;i++) {
if(map.containsKey(nums1[i])) {
map.put(nums1[i],map.get(nums1[i])+1);
} else {
map.put(nums1[i],1);
}
}
for(int i=0;i<nums2.length;i++) {
if(map.containsKey(nums2[i])) {
res.add(nums2[i]);
if(map.get(nums2[i]) > 1) {
map.put(nums2[i],map.get(nums2[i])-1);
} else {
map.remove(nums2[i]);
}
}
}
int[] result = new int[res.size()];
for(int i=0;i<res.size();i++) {
result[i] = (int)res.get(i);
}
return result;
}
}
参考答案:https://leetcode.com/problems/intersection-of-two-arrays-ii/
三种方法:
- 按照I的做法
- 直接使用List,判断List是否contains即可(分析得效率最低)
- 两个数组进行排序,使用两个指针求有序数组的交集
假设有k个交叉数,nums1长度n,nums2长度m,maxl=Math.max(n,m);
解法一(类似于I):
leetcode上用时8ms,时间复杂度O(k*maxl);空间复杂度最大为O(m+n)。
用时16ms,时间复杂度高O(mn),空间复杂度最大为O(m+n)。
最不合适的方法
用时5ms,时间复杂度O(maxl*log(maxl)),空间复杂度为O(k)
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
问题
- 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?(第一种比较好,nums1用hash表)
- 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?(如果能放下nums1就使用第一种,做成hash表;如果两个数组都放不下,就外部排序然后使用第三种)