-
Notifications
You must be signed in to change notification settings - Fork 4
/
350.Intersection_of_Two_Arrays_II.js
65 lines (65 loc) · 1.39 KB
/
350.Intersection_of_Two_Arrays_II.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersect = function (nums1, nums2) {
/**
* 解法:Map大法
*/
const count = (arr) => {
const map = new Map();
for (let i = 0; i < arr.length; i++) {
if (!map.has(arr[i])) {
map.set(arr[i], 1);
} else {
map.set(arr[i], map.get(arr[i]) + 1);
}
}
return map;
};
const nums1Map = count(nums1);
const nums2Map = count(nums2);
const minMap =
nums1Map.size === Math.min(nums1Map.size, nums2Map.size)
? nums1Map
: nums2Map;
const result = [];
for (const [key] of minMap) {
if (nums1Map.has(key) && nums2Map.has(key)) {
let i = Math.min(nums1Map.get(key), nums2Map.get(key));
while (i > 0) {
result.push(key);
i--;
}
}
}
return result;
/**
* 解法:数组构建
*/
const count = (arr) => {
const obj = {};
for (const num of arr) {
if (!obj[num]) {
obj[num] = 1;
} else {
obj[num]++;
}
}
return obj;
};
const count1 = count(nums1);
const count2 = count(nums2);
const min = {};
for (let key in count1) {
if (count1[key] && count2[key]) {
min[key] = Math.min(count1[key], count2[key]);
}
}
let result = [];
for (let num in min) {
result = [...result, ...new Array(min[num]).fill(num)];
}
return result;
};