Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Intersection of Two Arrays II #36

Open
@cheatsheet1999

Description

@cheatsheet1999

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Screen Shot 2021-09-12 at 8 42 57 PM

var intersect = function(nums1, nums2) {
    const map = new Map();
    for(let i of nums1) {
        if(map.has(i)) {
            map.set(i, map.get(i) + 1);
        } else {
            map.set(i, 1);
        }
    }
    
    let res = [];
    for(let i of nums2) {
        if(map.has(i) && map.get(i) > 0) {
            res.push(i);
            map.set(i, map.get(i) - 1);
        }
    }
    return res;
};
  • What if the given array is already sorted? How would you optimize your algorithm?
    • Using map built-in data structure in Javascript
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
    • in second for loop, we can check if the map has a frequence larger than 0, if larger than 0 it means first loop has more
      specific number than in the second loop.
  • 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?
    • Split the numeric range into subranges that fits into the memory. Modify code to collect counts only within a given subrange, and call the method multiple times (for each subrange).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions