Thief of Wealth

문제

N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때, 이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.

입력

첫째 줄에 자연수 N(1≤N≤100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1≤M≤100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들이 A안에 존재하는지 알아내면 된다. 모든 정수의 범위는 -231 보다 크거나 같고 231보다 작다.

출력

M개의 줄에 답을 출력한다. 존재하면 1을, 존재하지 않으면 0을 출력한다.

 

핵심 아이디어

이분탐색으로 찾으면된다!

최악의 경우 N,M이 각각 100000개 이므로 일반적인 방법으로는 시간초과가 나기 때문이다.

 

'use strict'

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

const binarySearch = (array, target, start, end) => {
    let mid = -1;
    while (start <= end) {
        mid = Math.floor((start + end) / 2);
        if (array[mid] === target) {
            return mid;
        } else if (array[mid] > target) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
    }
    return -1;
}

const solution = function (input) {
    const n = parseInt(input[0]);
    const A = input[1].split(" ").map(e => parseInt(e));
    const m = parseInt(input[2]);
    const B = input[3].split(" ").map(e => parseInt(e));
    let ans = '';
    A.sort((a, b) => a - b);

    B.forEach(
        (elem, idx) => {
            if (binarySearch(A, elem, 0, n - 1) !== -1) {
                ans += idx === m - 1 ? '1' : "1\n";
            } else {
                ans += idx === m - 1 ? '0' : '0\n';
            }
        }
    );

    console.log(ans);
};


const input = [];
rl.on("line", function (line) {
    input.push(line);
}).on("close", function () {
    solution(input);
    process.exit();
});

 

profile on loading

Loading...