-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitersectionOfTwoArraysII.js
More file actions
48 lines (41 loc) · 1.33 KB
/
itersectionOfTwoArraysII.js
File metadata and controls
48 lines (41 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* 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.
*/
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
/**
* iterate through nums1, generate map of num vs count like {1: 2, 2: 4}
* iterate through nums2, generate map of num vs count like {1: 2, 2: 4}
* iterate through smaller of nums1 map vs nums2 map, match the key with other map, compare whose value * (count) is smaller and push that to array
*/
var intersect = function(nums1, nums2) {
let numToCount1 = {};
nums1.forEach(num => {
numToCount1[num] = numToCount1[num] ? numToCount1[num] + 1 : 1;
});
let numToCount2 = {};
nums2.forEach(num => {
numToCount2[num] = numToCount2[num] ? numToCount2[num] + 1 : 1;
});
let intersections = [];
for(key of Object.keys(numToCount1)){
if (numToCount2[key]) {
while(numToCount2[key] > 0 && numToCount1[key] > 0){
numToCount2[key]--;
numToCount1[key]--;
intersections.push(parseInt(key));
}
}
}
return intersections;
};