알고리즘
백준 10815 숫자카드 js
Jaeilit
2022. 10. 4. 17:29
728x90
문제
https://www.acmicpc.net/problem/10815
10815번: 숫자 카드
첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,
www.acmicpc.net
정답코드
const fs = require("fs");
const filePath =
process.platform === "linux" ? "/dev/stdin" : "./이분탐색/10815/input.txt";
const input = fs.readFileSync(filePath).toString().trim().split("\n");
const [N, A, M, B] = input.map((v) => v.split(" ").map((x) => Number(x)));
const arys = A.sort((a, b) => a - b);
function binary(ary, target) {
let start = 0;
let end = ary.length - 1;
let result = 0;
while (start <= end) {
let mid = Math.floor((start + end) / 2);
if (ary[mid] >= target) {
end = mid - 1;
} else if (ary[mid] < target) {
start = mid + 1;
}
if (ary[mid] === target) {
result += 1;
}
}
return result;
}
let answer = [];
B.forEach((num) => {
answer.push(binary(arys, num));
});
console.log(answer.join(" "));
로직 설명
B 배열에서 A 배열에 몇개가 있는지 B 배열 순서 그대로 카운팅 해주면 되는데,
A배열을 이분탐색하기 위해 소팅해주고,
B배열을 ForEach 로 숫자 하나하나를 이분탐색에 넣어주면 된다.
나머지는 그냥 이분탐색 그 자체이기 때문에 무난하게 풀면 된다.
728x90