문제

programmers 프린터 문제 보러가기



풀이

import java.util.*;

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

		Queue<Print> queue = new LinkedList<>();
		List<Integer> list = new ArrayList<Integer>();

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

		while (true) {
			Integer max = Collections.max(list);
			int index = 0;

			while (true) {
				Print now = queue.poll();
				if (now.priority == max) {
					index = now.location;
					list.remove(max);
					break;
				} else {
					queue.add(now);
				}
            }
			answer++;
			if (index == location)
				return answer;
		}
	}

	static class Print {
		int priority, location;

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



문제점 해결

대기목록에서 우선순위가 가장 높은 순으로 프린트 되어야하기 때문에 List에 대기목록을 저장한 뒤 Collections를 사용해 max값을 찾은 뒤 queue에서 하나씩 숫자를 빼며 비교한다.max값과 다르다면 다시 queue에 넣어주고 max값과 일치한다면 몇 번 째로 프린터 하는지 index값과 location값이 같은지 비교하여 정답을 도출해낸다.