Skip to content

Commit ca90876

Browse files
author
Kohei Asai
authored
350. Intersection of Two Arrays II (#71)
1 parent 21732e6 commit ca90876

File tree

2 files changed

+173
-0
lines changed

2 files changed

+173
-0
lines changed
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
import intersect from "./intersectionOfTwoArrays2";
2+
3+
describe("350. Intersection of Two Arrays II", () => {
4+
test("#1", () => {
5+
expect(intersect([1, 2, 2, 1], [2, 2]).sort()).toEqual([2, 2].sort());
6+
});
7+
8+
test("#2", () => {
9+
expect(intersect([4, 9, 5], [9, 4, 9, 8, 4]).sort()).toEqual([4, 9].sort());
10+
});
11+
12+
test("#3", () => {
13+
expect(
14+
intersect(
15+
[
16+
61,
17+
24,
18+
20,
19+
58,
20+
95,
21+
53,
22+
17,
23+
32,
24+
45,
25+
85,
26+
70,
27+
20,
28+
83,
29+
62,
30+
35,
31+
89,
32+
5,
33+
95,
34+
12,
35+
86,
36+
58,
37+
77,
38+
30,
39+
64,
40+
46,
41+
13,
42+
5,
43+
92,
44+
67,
45+
40,
46+
20,
47+
38,
48+
31,
49+
18,
50+
89,
51+
85,
52+
7,
53+
30,
54+
67,
55+
34,
56+
62,
57+
35,
58+
47,
59+
98,
60+
3,
61+
41,
62+
53,
63+
26,
64+
66,
65+
40,
66+
54,
67+
44,
68+
57,
69+
46,
70+
70,
71+
60,
72+
4,
73+
63,
74+
82,
75+
42,
76+
65,
77+
59,
78+
17,
79+
98,
80+
29,
81+
72,
82+
1,
83+
96,
84+
82,
85+
66,
86+
98,
87+
6,
88+
92,
89+
31,
90+
43,
91+
81,
92+
88,
93+
60,
94+
10,
95+
55,
96+
66,
97+
82,
98+
0,
99+
79,
100+
11,
101+
81
102+
],
103+
[
104+
5,
105+
25,
106+
4,
107+
39,
108+
57,
109+
49,
110+
93,
111+
79,
112+
7,
113+
8,
114+
49,
115+
89,
116+
2,
117+
7,
118+
73,
119+
88,
120+
45,
121+
15,
122+
34,
123+
92,
124+
84,
125+
38,
126+
85,
127+
34,
128+
16,
129+
6,
130+
99,
131+
0,
132+
2,
133+
36,
134+
68,
135+
52,
136+
73,
137+
50,
138+
77,
139+
44,
140+
61,
141+
48
142+
]
143+
).sort()
144+
).toEqual(
145+
[5, 4, 57, 79, 7, 89, 88, 45, 34, 92, 38, 85, 6, 0, 77, 44, 61].sort()
146+
);
147+
});
148+
});

solutions/intersectionOfTwoArrays2.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// 350. Intersection of Two Arrays II
2+
// https://leetcode.com/problems/intersection-of-two-arrays-ii/
3+
export default function intersect(nums1: number[], nums2: number[]): number[] {
4+
const intersection: number[] = [];
5+
const sorted1 = [...nums1].sort((a, b) => a - b);
6+
const sorted2 = [...nums2].sort((a, b) => a - b);
7+
8+
let i1 = 0;
9+
let i2 = 0;
10+
11+
while (i1 < sorted1.length && i2 < sorted2.length) {
12+
if (sorted1[i1] === sorted2[i2]) {
13+
intersection.push(sorted1[i1]);
14+
15+
i1 += 1;
16+
i2 += 1;
17+
} else if (sorted1[i1] < sorted2[i2]) {
18+
i1 += 1;
19+
} else if (sorted1[i1] > sorted2[i2]) {
20+
i2 += 1;
21+
}
22+
}
23+
24+
return intersection;
25+
}

0 commit comments

Comments
 (0)