티스토리 뷰

문제보러가기

 

코딩테스트 연습 - 프린터

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

programmers.co.kr

우선 이문제는 큐를 이용해서 풀 수 있었다. 문제에 "들어온 순서대로" 라고 명시되어 있으므로 큐를 사용해야겠다는 접근은 어렵지 않았다!

 

문제풀이

-들어온 순서대로 먼저 확인해야하기 때문에 큐를 생성하여 넣는다.

-location을 함께 저장해서 문제에서 원하는 location의 문서가 몇번째인지 확인할 수 있도록 Pair클래스를 생성한다.

-우선순위가 더 높은 문서가 있다면 뒤로 밀리기 때문에 남은 인쇄요청중 우선순위가 높은걸 확인할 수 있게 PriorityQueue를 이용한다.

 

 

import java.util.Collections;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
class Solution {
    public int solution(int[] priorities, int location) {
      Queue<Pair> queue = new LinkedList<>();
		PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(Collections.reverseOrder());
		int cnt=1;
		//location과 우선순위를 함께 큐에 저장
        //문서의 우선순위를 확인하기위해 PriorityQueue를 이용
		for(int i=0;i<priorities.length;i++) {
			queue.add(new Pair(i,priorities[i]));
			priorityQueue.add(priorities[i]);
		}
		while(!queue.isEmpty()) {
        	//현재 프린트하려는 문서의 우선순위보다 높은 우선순위의 문서가 없는지 확인
			if(queue.peek().priority == priorityQueue.peek()) {
            	//순서를 확인하려는 문서인지 체크
				if(queue.peek().location==location) {
					return cnt;
				}
                //순서를 확인하려는 문서가 아니라면 큐에서 제거해주고 순서를 증가시켜준다.
				queue.poll();
				priorityQueue.poll();
				cnt++;
			}
            //더 높은 우선순위의 문서가 존재할 경우 해당문서는 인쇄요청 마지막 순서로 돌아간다.
			else {
				Pair p = queue.poll();
				queue.add(p);
			}
			
			
		}
		return cnt;
	}
	

}
class Pair{
	int location;
	int priority;
	Pair(int location,int priority){
		this.location = location;
		this.priority = priority;
	}
}

다른분들의 풀이를 보면 굉장히 깔끔하고 이렇게도 풀 수 있구나 싶었다.. 더 간결하고 좋은 코드를 짜기위해 공부해야겠다고 다짐했...ㅎ

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함