본문 바로가기

PROGRAMMING/ALGORITHM

[프로그래머스] 프린터 JAVA QUEUE

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

 

코딩테스트 연습 - 프린터

일반적인 프린터는 인쇄 요청이 들어온 순서대로 인쇄합니다. 그렇기 때문에 중요한 문서가 나중에 인쇄될 수 있습니다. 이런 문제를 보완하기 위해 중요도가 높은 문서를 먼저 인쇄하는 프린

programmers.co.kr

 

풀이방법

우선 FIFO로직인 프린터 임으로 queue를 사용해 풀기로 설계.

로직은

1. 현재 맨 앞에 있는 인쇄물의 우선순위보다 높은 우선순위를 갖는 인쇄물이 있는지 파악

   2-1. 없다면 Pool 

      2-1-2. 입력받은 위치의 인쇄물이 출력된 경우 출력순번을 RETURN

   2-2. 있다면 Offer(Pool) 다시 넣는 작업을 진행

 

코드

import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        int length = priorities.length;
        Queue<int[][]> queue = new LinkedList<>();

        for(int i=0; i<priorities.length; i++){
            int[][] docs = new int[1][2];
            docs[0][0] = priorities[i]; //우선순위
            docs[0][1] = i; //위치
            queue.add(docs);
        }

        while(!queue.isEmpty()){
            //우선순위 체크
            int[][] peek = queue.peek();
            int peekPrior = peek[0][0];
            int peekLoc = peek[0][1];
            boolean isPrior = true;
            for(int[][] doc : queue){
                if(doc[0][0] > peekPrior) isPrior = false;
            }
            if(isPrior){
                //peek가 우선순위가 가장 높다면 POOL
                int[][] temp = queue.poll();
                answer++;
                if(peekLoc == location){
                      return answer;
                }
            }else {
                //peek보다 우선순위가 높은게 있다면 POOL -> OFFER
                queue.offer(queue.poll());
            }
        }
        return answer;
    }
}