Notice
Recent Posts
Recent Comments
Link
ยซ   2024/12   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
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
Archives
Today
Total
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Lennon FE

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.3] ์ž…๊ตญ์‹ฌ์‚ฌ ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.3] ์ž…๊ตญ์‹ฌ์‚ฌ

Lennon 2022. 3. 1. 18:55
728x90
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/43238?language=javascript 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ž…๊ตญ์‹ฌ์‚ฌ

n๋ช…์ด ์ž…๊ตญ์‹ฌ์‚ฌ๋ฅผ ์œ„ํ•ด ์ค„์„ ์„œ์„œ ๊ธฐ๋‹ค๋ฆฌ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ์ž…๊ตญ์‹ฌ์‚ฌ๋Œ€์— ์žˆ๋Š” ์‹ฌ์‚ฌ๊ด€๋งˆ๋‹ค ์‹ฌ์‚ฌํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์€ ๋‹ค๋ฆ…๋‹ˆ๋‹ค. ์ฒ˜์Œ์— ๋ชจ๋“  ์‹ฌ์‚ฌ๋Œ€๋Š” ๋น„์–ด์žˆ์Šต๋‹ˆ๋‹ค. ํ•œ ์‹ฌ์‚ฌ๋Œ€์—์„œ๋Š” ๋™์‹œ์— ํ•œ

programmers.co.kr

const binarySearch = (times, n) => {
    let left = 0;
    let right = n * times[times.length - 1];
    let middle, people;
    
    while(left <= right) {
        middle = Math.floor((left + right) / 2);
        
        people = times.reduce((prev, cur) => prev + Math.floor(middle/cur), 0);
        
        if(people >= n) {
            right = middle - 1;
        } else {
            left = middle + 1;
        }
    }
    
    return left;
}

function solution(n, times) {
    times = times.sort((a,b) => a-b);
    return binarySearch(times,n);
}

์ด๋ถ„ํƒ์ƒ‰ ๋ฌธ์ œ์ด๋‹ค. 

 

์ž…๋ ฅ์„ ์˜ˆ๋กœ๋“ค๋ฉด ์ตœ์†Œ์‹œ๊ฐ„์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋ฏ€๋กœ ์ตœ์†Œ๊ฐ’(left)๋Š” 1๋กœ ๋‘๊ณ , ์ตœ๋Œ€๊ฐ’์€ ์ •๋ ฌ๋œ times๋ฐฐ์—ด์˜ ๋งˆ์ง€๋ง‰ ๊ฐ’์— ์ธ์›์ˆ˜๋ฅผ ๊ณฑํ•œ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ์ž.  right = 10 * 6 = 60

 

๊ทธ ํ›„ while๋ฌธ์„ ๋Œ๋ฉฐ ์ด๋ถ„ ํƒ์ƒ‰์„ ํ•˜๋ฉด๋œ๋‹ค.

 

n = 6, times = [7, 10]

 

์ฒซ ๋ฒˆ์งธ ๋ฐ˜๋ณต

middle๊ฐ’ => Math.floor((0+60)/2) => 30

people๊ฐ’ => Math.floor(30/7) + Math.floor(30/10) => 7

 

7์€ ์šฐ๋ฆฌ๊ฐ€ ๊ฐ€์ง„ n๊ฐ’๋ณด๋‹ค ํฌ๋ฏ€๋กœ right๊ฐ’์„ middle - 1 ๊ฐ’์œผ๋กœ ์ง€์ •ํ•ด์ค€๋‹ค.

 

๋‘ ๋ฒˆ์งธ ๋ฐ˜๋ณต

middle๊ฐ’ => Math.floor((0+29)/2)  => 14

people๊ฐ’ => Math.floor(14/7) + Math.floor(14/10) => 3

 

3์€ ์šฐ๋ฆฌ๊ฐ€ ๊ฐ€์ง„ n๊ฐ’๋ณด๋‹ค ํ˜„์ €ํžˆ ์ž‘์œผ๋ฏ€๋กœ left๊ฐ’์„ middle + 1๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.

 

์„ธ ๋ฒˆ์งธ ๋ฐ˜๋ณต

middle๊ฐ’ => Math.floor((15+29)/2) => 22

people๊ฐ’ => Math.floor(22/7) + Math.floor(22/10) => 5

 

3์€ ์šฐ๋ฆฌ๊ฐ€ ๊ฐ€์ง„ n๊ฐ’๋ณด๋‹ค ํ˜„์ €ํžˆ ์ž‘์œผ๋ฏ€๋กœ left๊ฐ’์„ middle + 1๋กœ ๋ฐ”๊ฟ”์ค€๋‹ค.

 

.

.

.

 

์ •๋‹ต์ด ๊ตฌํ•ด์งˆ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฉด left๊ฐ’์ด right๊ฐ’๊ณผ ๊ฐ™์•„์ง€๊ฑฐ๋‚˜ ๋„˜์„ ๋•Œ ์šฐ๋ฆฌ๊ฐ€ ์›ํ•˜๋Š” ๊ฐ’(์ตœ์†Œ์‹œ๊ฐ„)์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

์ •๋‹ต์ด 30์ด์–ด๋„ ๋˜์ง€๋งŒ left >= right๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜๋ฏ€๋กœ ์ตœ์†Œ์‹œ๊ฐ„์„ ๊ตฌํ•  ์ˆ˜ ์žˆ์Œ

728x90
๋ฐ˜์‘ํ˜•
Comments