Skip to content

Commit 09d99f1

Browse files
author
zongyanqi
committed
add Easy_349_Intersection_of_Two_Arrays
1 parent f3208c8 commit 09d99f1

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Given two arrays, write a function to compute their intersection.
3+
4+
Example:
5+
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
6+
7+
Note:
8+
Each element in the result must be unique.
9+
The result can be in any order.
10+
*/
11+
12+
/**
13+
* @param {number[]} nums1
14+
* @param {number[]} nums2
15+
* @return {number[]}
16+
*/
17+
var intersection = function (nums1, nums2) {
18+
19+
var ret = [];
20+
var map1 = nums1.reduce((map, n) => {
21+
if (!map[n]) map[n] = 1;
22+
return map;
23+
}, {});
24+
25+
var map2 = nums2.reduce((map, n) => {
26+
if (map1[n] && !map[n]) {
27+
ret.push(n);
28+
map[n] = 1;
29+
}
30+
return map;
31+
}, {});
32+
33+
return ret;
34+
};
35+
console.log(intersection([1, 2, 2, 1], [2, 2]));

0 commit comments

Comments
 (0)