본문 바로가기
Algorithm/프로그래머스(Programmers)

[ 자바스크립트(JavaScript) ] 프로그래머스 level2 - 프린터

by YWTechIT 2021. 10. 19.
728x90

📍 프로그래머스 2단계 - 프린터

프로그래머스 2단계 - 프린터


⚡️ 나의 풀이

스택/큐를 이용한 문제인데, 중요도에 따라 출력해야 하는 문서가 달라지므로 주의한다. location과 동일한 index를 쉽게 찾기 위해 index 배열을 새로 만들어 priorities.length만큼 index의 값을 주었다.

 

  1. prioritiesmax값을 찾는다.
  2. priorities[0]값과 max가 동일한지 확인한다.(중요도가 가장 높은 문서인지 확인하는 작업) max값과 동일하면 shift시키는데, 이때 location이랑 동일한지도 확인한다.
  3. priorities[0]값과 max가 동일하지 않으면 나머지 목록 중 중요도가 높은 문서가 있으므로 제일 뒤로 보낸다. arr.push(arr.shift())

 

728x90

 

function solution(priorities, location) {
    let n = priorities.length;
    let index = Array.from({ length: n }, (v, k) => k);
    let cnt = 1;

    while (priorities.length !== 0) {
        let max = Math.max.apply(null, priorities);
        if (max === priorities[0]) {
            if (index[0] === location) return cnt;
            else priorities.shift(), index.shift(), cnt++;
        } else {
            priorities.push(priorities.shift());
            index.push(index.shift());
        }
    }
}
반응형

댓글