본문 바로가기

Algorithm

[Algorithm/Java][프로그래머스] 프린터

반응형

[프로그래머스] 프린터

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

문제접근

인쇄 대기열에서 우선순위가 높은 것 부터 인쇄를 해야하고, location에 있는 작업이 몇번째로 인쇄되는지를 구해야한다.
그래서 task 클래스를 만들어 우선순위와 처음 주어진 인덱스를 저장하고 이를 큐에 저장을 하고,
가장 큰 우선순위를 표현하기위해서 우선순위 큐를 이용해서 최대 힙을 이용했다.
그래서 해당 location에 있는 작업이 인쇄될 때까지 while문을 돌리도록 했다.

Code

import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Collections;
import java.util.LinkedList;

class Solution {
    class task {
        int priority;
        int index;
        public task(int priority, int index) {
            this.priority = priority;
            this.index = index;
        }
    }
    public int solution(int[] priorities, int location) {
    int answer = 0;
        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // 최대 힙 생성(우선순위를 내림차순으로 저장)
        Queue<task> print = new LinkedList<>(); //프린트 인쇄 대기열을 큐에 저장
    for(int i = 0; i<priorities.length; i++){
        print.add(new task(priorities[i],i));
        pq.add(priorities[i]);
    }
    while(!print.isEmpty()){
        // 우선순위에 따라서 프린트의 인쇄를 진행
        task cur = print.poll();
        if(cur.priority == pq.peek()){
            answer++;
            if(cur.index == location) break;
            pq.poll();
        } else {
            print.add(cur);
        }
    }
    return answer;
    }
}

어려웠던 점 / 배운 점 / 느낀 점

프린트의 작업을 큐와 우선순위 큐를 이용해서 구현하였다.
원래 기본 우선순위 큐는 오름차순으로 정렬되는 최소 힙이기 때문에 생성할 때, Collections.reverseOrder()를 이용해서 내림차순으로 저장되는 맥스힙으로 바꿔주었다.

반응형