您的位置:首页 > 其它

Leetcode_350_Intersection of Two Arrays II

2016-08-22 21:13 399 查看
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?

Subscribe to see which companies asked this question

思路:

(1)题意为给定两个整形数组,求两数组的交集,出现多次的也要包含在内。

(2)通常情况下,我们会考虑使用Map来解决。首先,将第一个数组中的元素存储到map中,其中key为数组中元素的值,value为数组中某一元素出现的次数。其次,遍历第二个数组,判断其是否包含于map的keys中(对应的value值大于0),如果包含,则存储该元素到数组中,且将map中该元素对应的value减1;不包含则继续遍历。最后,所得数组即为所求。

(3)上题中最后所示note还有三个问题,这里给出简单的思路。

问题1:如果所给的数组是已经排好序的,选择什么算法好呢?答:可以考虑设置两个指针,分别从两数组的起始位置往后遍历,找到相同的元素就存储,具体细节不累赘。

问题2:如果数组1的大小要远远小于数组2的大小用什么算法比较好?答:由于数组是排好序的,又数组1非常小,问题就退化为从一个很大的数组中寻找若干指定元素的问题了,可以考虑使用二分查找进行处理。

问题3:如果数组2排好序非常大且存储在本地磁盘,内存无法一次全部加载进来时用什么算法比较好?答:考虑使用分治。数组2已排好序,可以一次加载若干小于内存大小的元素到内存中进行比较,进行多次比较即可选出。

(4)算法代码实现如下所示。希望对你有所帮助。

package leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author liqqc
*/
public class Intersection_of_Two_Arrays_2 {

public static void main(String[] args) {
int[] intersect = intersect(new int[]{1},new int[]{1,2});
System.err.println(intersect);
}

public static 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>();
for (int i : nums1) {
if(map.get(i)==null) {
map.put(i, 1);
}else{
map.put(i,map.get(i)+1);
}
}

List<Integer> rt = new ArrayList<>();
for (int i : nums2) {
if(map.get(i) != null &&  map.get(i) !=0) {
rt.add(i);
map.put(i, map.get(i)-1);
}
}
int[] arr = new int[rt.size()];
for (int i = 0; i < rt.size(); i++) {
arr[i] = rt.get(i);
}
return arr;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: