Open
Description
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.
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.
- 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
- 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
Labels
No labels