-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.js
51 lines (42 loc) · 883 Bytes
/
2.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
// Title: 공통 원소 구하기
// 방법 1
// Time: O(nlogn+mlogm)
// Space: O(n+m)
function main(n, n1, m, m1) {
n1.sort((a, b) => a - b);
m1.sort((a, b) => a - b);
let result = "";
let lt = 0;
let rt = 0;
while (lt < n && rt < m) {
if (n1[lt] === m1[rt]) {
result += `${n1[lt]} `;
lt++;
rt++;
continue;
}
if (n1[lt] > m1[rt]) {
rt++;
} else {
lt++;
}
}
console.log(result);
}
// 방법 2
// Time: O((n+m)log(n+m))
// Space: O(n+m)
function main(n, n1, m, m1) {
const assemble = [...n1, ...m1].sort((a, b) => a - b);
const hash = new Map();
let result = "";
for (let i = 0; i < n + m; i++) {
if (hash.get(assemble[i])) {
result += `${assemble[i]} `;
continue;
}
hash.set(assemble[i], true);
}
console.log(result);
}
main(5, [3, 2, 5, 7, 8], 5, [1, 3, 9, 5, 2]);