[문제 링크]

코딩테스트 연습 - 프린터

[풀이 과정]

방법 1(일반 큐를 사용한 방법)

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

class Solution {

    public class Print {
        private int priority;
        private int location;

        public Print(int priority, int location) {
            this.priority = priority;
            this.location = location;
        }
    }

    public int solution(int[] priorities, int location) {
        int answer = 0;

        Queue<Print> queue = new LinkedList<>();

        for (int i = 0; i < priorities.length; i++)
            queue.add(new Print(priorities[i], i)); // -> (2,0), (1,1), (3,2), (2,3)

        while (!queue.isEmpty()) {
            Print print = queue.poll();

            boolean ifUpperPriorityExist = false;

            for (Print tmp : queue) {
                if (print.priority < tmp.priority) {
                    ifUpperPriorityExist = true;
                    break; // for문 탈출
                }
            }

            if (ifUpperPriorityExist) queue.add(print);
            else {
                answer++;
                if (print.location == location) break; // 바깥 for문 탈출
            }
        }

        return answer;
    }

    public static void main(String[] args) {
        int[] priorities = {2, 1, 3, 2};

        Solution solution = new Solution();
        System.out.println(solution.solution(priorities, 0));
    }
}

앞에서 부터 출력이 되는데 우선 순위가 낮으면 프린터에서 나와서 맨 뒤로 들어가고, 아니면 출력된다?

선입선출, 그리고 자료를 추가하면 맨 뒤로 들어가는 큐를 사용하자!

  1. Print 클래스를 만들어서, 큐에 객체를 추가하여 우선 순위와 위치(인덱스)를 같이 비교할 수 있게 한다.
  2. 입력받은 priorities 배열의 크기만큼 반복문을 순회하면서, 큐에 자료들을 넣어준다.
  3. 큐가 빈 값이 될때 까지 조건문을 수행하고, 큐의 맨 앞 객체를 poll 한다.
  4. poll 한 객체의 우선순위보다 큐에 더 큰 우선순위의 객체가 존재하는 경우, poll 한 객체를 다시 큐에 넣는다.
  5. 반대로, poll 한 객체의 우선순위보다 큐에 더 큰 우선순위의 객체가 존재하지 않는 경우, answer1 증가한다.
  6. 마지막으로, 입력받았던 location (인쇄를 요청한 문서가 몇 번째로 인쇄되는지) 이 poll 한 큐의 객체의 location 과 같으면 반복문을 나오고, answer 를 리턴한다.

[결과]

Untitled