알고리즘
[백준] 숫자카드(10815)
17 views
블로그 불러오는 중...
알고리즘

// 백준에서는 첫번째 조건으로 input 받게 설정
// 내 맥북, desktop 에선 두번째걸로 선택됨
const input =
process.platform === "linux"
? require("fs").readFileSync("/dev/stdin").toString().split("\n")
: require("fs").readFileSync("./input.txt").toString().split("\n");
const numberArray = input[1]
.split(" ")
.map((el) => parseInt(el))
.sort((a, b) => a - b);
const testArray = input[3].split(" ").map((el) => parseInt(el));
// 정렬된 Array 반환
const binarySearch = (arr, number) => {
let end = arr.length - 1;
let start = 0;
while (start <= end) {
const mid = parseInt((end + start) / 2);
if (start === end) {
return arr[mid] === number;
}
if (arr[mid] > number) {
end = mid;
} else if (arr[mid] < number) {
start = mid + 1;
} else {
return true;
}
}
return false;
};
let answer = "";
for (const num of testArray) {
answer += binarySearch(numberArray, parseInt(num)) ? " 1" : " 0";
}
console.log(answer.trim());해당 문제는 이진탐색으로 해당 수가 배열에 있는지 찾아 풀면 되는 문제이다.
사실 해당 배열을 for 문을 통해 해쉬에 저장하고, 해당 값이 있는지 없는지를 찾아서 계산하는 것이 조금 더 효율적일 것 같으나, 문제 분류가 이진 탐색이라 이진 탐색으로 풀어 보았다.