Leetcode_350_Intersection of Two Arrays II

本文介绍了一种计算两个整数数组交集的算法,包括多个优化思路。主要通过使用Map存储第一个数组元素及其出现次数,遍历第二个数组并匹配。此外还讨论了不同场景下的最优解法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值