leetcode 350. Intersection of Two Arrays II

257 篇文章 17 订阅

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?
1. 如果仅仅是nums2大得内存容纳不下,那么把nums1中的所有元素放入hashmap,然后一个个读取nums2中能被内存容纳下的数组块,记录下交集。
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值