๐Ÿ”ฅ Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.2] ํ”„๋ฆฐํ„ฐ (js)

Lennon 2021. 11. 10. 22:30
728x90
๋ฐ˜์‘ํ˜•

https://programmers.co.kr/learn/courses/30/lessons/42587

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ํ”„๋ฆฐํ„ฐ

์ผ๋ฐ˜์ ์ธ ํ”„๋ฆฐํ„ฐ๋Š” ์ธ์‡„ ์š”์ฒญ์ด ๋“ค์–ด์˜จ ์ˆœ์„œ๋Œ€๋กœ ์ธ์‡„ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์ค‘์š”ํ•œ ๋ฌธ์„œ๊ฐ€ ๋‚˜์ค‘์— ์ธ์‡„๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ๋ณด์™„ํ•˜๊ธฐ ์œ„ํ•ด ์ค‘์š”๋„๊ฐ€ ๋†’์€ ๋ฌธ์„œ๋ฅผ ๋จผ์ € ์ธ์‡„ํ•˜๋Š” ํ”„๋ฆฐ

programmers.co.kr

 

function solution(priorities, location) {    
    let result = [];
    let prior = [];
    let max = 0; 
    let answer;
    
    for(let i = 0; i < priorities.length; i++){
        prior.push({idx : i, value : priorities[i]});
    }
    
    for(let j = 1; j < prior.length; j++){
        for(let i = 0; i < prior.length; i++){
            max = Math.max(prior[i].value, max);
        }
        if(max === prior[0].value){
            result.push(prior[0]);
            prior.shift();
            j = 0;
        }
        else if(prior[0].value < prior[j].value){
            prior.push(prior[0]);
            prior.shift();
            j = 0;
        }
        max = 0;
    }
    const ans = [...result, ...prior].filter((a,b) => {
        if(a.value === priorities[location] && a.idx === location){
            answer = b;
        }
    });
    return answer+1;
}

 

์ธ๋ฑ์Šค๋„ ๊ธฐ๋กํ•ด์•ผํ•˜๊ณ , ์ˆœ์„œ๋„ ์ œ๋Œ€๋กœ ๊ตฌํ•ด์•ผ๋ผ์„œ ๊ฐ์ฒด๋กœ ํ’€์—ˆ๋‹ค.

 

๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ฐพ์€ ํ›„ ์•ž์—์„œ ํ•˜๋‚˜ ์”ฉ shiftํ•˜๋ฉฐ ๋’ค์— ๊ฐ’์„ ๋น„๊ตํ•ด result ๋ฐฐ์—ด์„ ์ฑ„์›Œ๋‚˜๊ฐ”๋‹ค.

 

๊ณ„์† j=0์œผ๋กœ ์ด๋™ ํ›„ ์ตœ๋Œ€๊ฐ’์„ ๊ตฌํ•œ ํ›„ ์ฒ˜์Œ๋ถ€ํ„ฐ ๋ฐ˜๋ณตํ•ด ํšจ์œจ์ ์ธ ์ฝ”๋“œ๋Š” ์•„๋‹Œ ๊ฒƒ ๊ฐ™๋‹ค.

(์ตœ๋Œ€๊ฐ€ 100๊ฐœ ์ดํ•˜๋ผ์„œ ๊ทธ๋ƒฅ ํ–ˆ์Œ)

 

๋‹ค์Œ์—” ๋” ์ข‹์€ ์ฝ”๋“œ ๋ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ƒ๊ฐํ•ด๋ด์•ผ๊ฒ ๋‹ค.

 

 

728x90
๋ฐ˜์‘ํ˜•