[Algorithm] 350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

 

Not good enough approach

复制代码
var intersect = function(nums1, nums2) {
    let r = [];
    // get larger array
    const len1 = nums1.length;
    const len2 = nums2.length;
    
    // larger & smaller
    const larger = len1 > len2 ? nums1: nums2;
    const smaller = len1 > len2 ? nums2: nums1;
    
    // conver larger array to object
    let hashed = {};
    for (let n of larger) {
        if (n in hashed) {
            hashed[n]++;
        } else {
            hashed[n] = 1;
        }
    }
 
    // loop over smaller array
    for (let n of smaller) {
        if (`${n}` in hashed) {
            r.push(n);
            hashed[n] = hashed[n]-1;
            if (hashed[n] === 0) {
                delete hashed[n];
            }
        }
    }
    
    return r;
};
复制代码

 

The reason that code above is not good enough is because, \

1. we use larger array as lookup, this cause more memory usage. -- actually we need to use smaller array as lookup

2. we use 'len1, len2, samller, larger' extra storage, we can actully swap nums1 and nums by one extra function call.

复制代码
var intersect = function(nums1, nums2) {

    if (nums1.length > nums2.length) {
        return intersect(nums2, nums1);
    }
    
    // conver samller array to object
    let hashed = {};
    for (let n of nums2) {
        if (n in hashed) {
            hashed[n]++;
        } else {
            hashed[n] = 1;
        }
    }
    
    let r = [];
    // loop over smaller array
    for (let n of nums1) {
        if (hashed[n] > 0) {
            r.push(n);
            hashed[n] = hashed[n]-1;
        }
    }
    
    return r;
}
复制代码

 

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?

Will write another post for the follow up questions.

 

posted @   Zhentiw  阅读(136)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2018-12-14 [Algorithm] Linked List Data Structure in JavaScript
2017-12-14 [React] Use Prop Collections with Render Props
2016-12-14 [JS Compse] 4. A collection of Either examples compared to imperative code
2015-12-14 [AngularJS] Services, Factories, and Providers -- value & Providers
2015-12-14 [AngularJS] Services, Factories, and Providers -- Service vs Factory
2014-12-14 [MongoDB] Query, update, index and group
点击右上角即可分享
微信分享提示