๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

์ด๋ถ„๊ฒ€์ƒ‰ ๋ณธ๋ฌธ

๋ฌธ์ œ(์ถœ์ฒ˜ : ์ธํ”„๋Ÿฐ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด ๊ฐ•์˜, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ)

์ž„์˜์˜ N๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. N๊ฐœ์˜ ์ˆ˜๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ ๋‹ค์Œ N๊ฐœ์˜ ์ˆ˜ ์ค‘ ํ•œ ๊ฐœ์˜ ์ˆ˜์ธ M์ด ์ฃผ์–ด์ง€๋ฉด ์ด๋ถ„๊ฒ€์ƒ‰์œผ๋กœ M์ด ์ •๋ ฌ๋œ ์ƒํƒœ์—์„œ ๋ช‡ ๋ฒˆ์งธ์— ์žˆ๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”. ๋‹จ ์ค‘๋ณต๊ฐ’์€ ์กด์žฌํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— ํ•œ ์ค„์— ์ž์—ฐ์ˆ˜ N(3<=N<=1,000,000)๊ณผ M์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๋‘ ๋ฒˆ์งธ ์ค„์— N๊ฐœ์˜ ์ˆ˜๊ฐ€ ๊ณต๋ฐฑ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

 

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ ์ค„์— ์ •๋ ฌ ํ›„ M์˜ ๊ฐ’์˜ ์œ„์น˜ ๋ฒˆํ˜ธ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1
8 32
23 87 65 12 57 32 99 81

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ 1

3

 

Tip

 

๋ฌธ์ œํ’€์ด

//๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ๋‹ต
function solution(arr,num){
    let answer;
    arr = arr.sort((a,b)=>a-b);
    let leftPoint = 0;
    let rightPoint = arr.length-1;
    let middle = Math.floor((leftPoint + rightPoint) / 2);

    while(arr[middle] !== num && leftPoint <= rightPoint){
        if(num < arr[middle]){
            rightPoint = middle-1;
        }else if(num > arr[middle]){
            leftPoint = middle+1;
        }
        middle = Math.floor((leftPoint + rightPoint) / 2)
    };

    if(arr[middle] === num){
        answer = middle+1;
    }
    return answer;
}

let arr = [23,87,65,12,57,32,99,81];
console.log(solution(arr,32))