Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Intersection of Two Arrays II #36

Open
cheatsheet1999 opened this issue Sep 13, 2021 · 0 comments
Open

Intersection of Two Arrays II #36

cheatsheet1999 opened this issue Sep 13, 2021 · 0 comments

Comments

@cheatsheet1999
Copy link
Owner

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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant