알고리즘문제

프로그래머스 > 프린터

단점이없어지고싶은개발자 2022. 11. 2. 23:16
반응형

 

 

function solution(priorities, location) {
    const answer = [];
    const waitList = priorities.map((x, i) => [x, i]);
    //i를 통해 location위치를 반환시켜주기 위해 배열로 만들어준다.
    while (waitList.length) {
        const front = waitList.shift();
        //큐처럼 앞에서 빼준다.
        if (front[0] >= Math.max(...waitList.map(x => x[0]))) {
        //만약 Math.max로 큰 숫자보다 큰게 있다면 answer에 담아준다. front[1]을 넣어주는 이유는
        //index는 여기서 고유하게 쓰일 수 있다. 
            answer.push(front[1]);
            if (front[1] === location) {
            //만약 location과 i인 front[1]이 같다면 이미 자기보다 큰 숫자가 우선순위에 들어간 상태가 된다.
                break;
            }
        } else {
            waitList.push(front);
            //이렇게 되면 wiatList의 스택처럼 쌓이게 된다.
        }
    }
    
    return answer.indexOf(location) + 1;
    //해당 위치에서 +1
}
반응형