프로그래머스 | 프린터 (Java)

mul·2023년 2월 27일
0

코딩테스트연습

목록 보기
30/56

🔒 문제

프로그래머스 Lv.2 스택/큐 프린터

🔑 해결

현재 대기목록에 있는 문서의 중요도가 순서대로 담긴 배열 priorities와 내가 인쇄를 요청한 문서가 현재 대기목록의 어떤 위치에 있는지를 알려주는 location이 매개변수로 주어질 때, 내가 인쇄를 요청한 문서가 몇 번째로 인쇄되는지 return하도록 solution함수를 작성하는 문제이다.

현재 대기목록의 위치(location)와 우선순위(proority)를 담을 Document 클래스를 생성하여 사용하였다. 대기목록(queue)과 인쇄되는 목록(list)를 생성하여, 인쇄되는 문서의 location이 내가 인쇄를 요청한 문서의 location과 같을 때까지 규칙에 따라 큐에 넣고 삭제하는 작업을 반복한다.

  1. location(현재위치)과 priority(우선순위)를 가지는 Document클래스를 작성
  2. queue 형태의 LinkedList queue를 생성한 후, for문을 돌려 Document를 생성하여 queue에 add
  3. 인쇄되는 목록을 저장할 ArrayList list와 list에 추가되는 목록의 location을 저장할 target 선언
  4. target이 내가 요청한 문서의 위치(location)과 같을 때까지 while문을 돌린다
    4-1. queue의 가장 앞에 위치한 Document를 꺼내어 first에 저장
    4-2. 가장 앞에 위치한 문서를 제외한 나머지 문서를 for문을 통해 탐색하면서 first보다 중요도가 높은 문서(first.priority < queue.get(i).priority)가 존재하면 first문서를 삭제하고 다시 넣어 큐의 가장 마지막에 넣는다. 중요도가 높은 우선순위가 존재하므로 nhp(no high priority)에 false 저장하고 break
    4-3. 반복문을 끝낸 nhp가 true라면 first보다 높은 우선순위가 존재하지 않는 것이므로 list에 first에 add하고 queue에서 삭제
    4-4. target에 first의 location을 저장
  5. target이 내가 요청한 문서의 위치(location)과 같다면 while문을 끝내고, answer에 list.size()를 저장

🔓 코드

import java.util.ArrayList;
import java.util.LinkedList;
class Solution {
    class Document {
		int location;
		int priority;
		
		public Document(int location, int priority) {
			super();
			this.location = location;
			this.priority = priority;
		}
	}
	
    public int solution(int[] priorities, int location) {
        int answer = 0;
        
        LinkedList<Document> queue = new LinkedList<>();
        for (int i = 0; i < priorities.length; i++) {
        	Document doc = new Document(i, priorities[i]);
        	queue.add(doc);
        }
        
        ArrayList<Document> list = new ArrayList<>();
        int target = -1;
        
        while(target != location) {
        	Document first = queue.getFirst(); // 대기목록의 가장 앞에 있는 문서
        	boolean nhp = true; // 중요도가 높은 문서 존재 여부
        	for (int i = 1; i < queue.size(); i++) {
				if (first.priority < queue.get(i).priority) {
					nhp = false;
					queue.remove();
					queue.add(first);
					break;
				}
			}
        	if (nhp) {
        		list.add(first);
        		queue.remove();
        		target = first.location;
        	}
        }
        
        answer = list.size();
        
        return answer;
    }
}

0개의 댓글