[프로그래머스] 프린터

jr_necki·2022년 8월 1일
0

프로그래머스

목록 보기
1/1

문제보기

🚩 내 코드

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

public class Solution {
    class Task{
        int location;
        int priority;
        public Task(int location, int priority) {
            this.location = location;
            this.priority = priority;
        }
    }
    public int solution(int[] priorities, int location) {
        int answer = 0;

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

        for(int i=0; i<priorities.length; i++){
            queue.add(new Task(i, priorities[i]));
        }

        int now=0;
        while(!queue.isEmpty()){
            Task cur = queue.poll();
            boolean flag = false;
            for(Task t : queue){
                if(t.priority>cur.priority){
                    flag = true;
                }
            }
            if(flag) { // 우선순위 높은게 있으면 뒤로 보낸다
                queue.add(cur);
            }else{
                now++;
                if(cur.location == location) {
                    answer = now;
                    break;
                }

            }
        }
        return answer;
    }
}

💡 푼 방식

대기 목록을 task라는 클래스를 생성하여 큐에 넣었고, 클래스는 우선 순위와 위치 변수를 가졌다.
문제 그대로, 큐를 돌려서 해당 task가 큐안에 있는 task와 우선순위를 비교하여 우선순위가 높은 것이 있다면 뒤로 보냈다. 그렇지 않다면 위치를 확인하여 문제가 원하는 위치였던 task였으면 그것이 답이다.

📚 알게 된 정보

PriorityQueue

Queue 인터페이스의 구현체 중 하나, 저장 순서와 상관 없이 우선순위가 높은 것부터 꺼내진다.

PriorityQueue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder()); // 이건 반대로

우선순위가 높은 것부터 꺼낸다 지, 우선순위가 높은 순으로 보관한다는 뜻이 아니다.
따라서 PriorityQueue를 그대로 출력했을 때와 실제로 요소를 하나씩 출력했을 때 표시되는 순서에는 차이가 있을 수 있다.

for(int priority:priorities){
	queue.offer(priority);
}

// 기존 배열에서 일치하는 문서 찾기
while(!queue.isEmpty()){
	for(int i=0; i<priorities.length; i++){
    	if(queue.peek() == priorities[i]){
        	if(i==location){
            	return answer;
            }
            answer++;
            queue.poll();
        }
    }
}
profile
슉슉슉

0개의 댓글