https://school.programmers.co.kr/learn/courses/30/lessons/42587
주어진 인덱스에 있는 문서가 몇번째 인쇄인지 구하는 문제이다.
들어오는 배열은 문서를 구분할 수 있는 번호가 주어진 게 아니라, 문서의 중요도(출력 순서)가 들어있는 배열이다. 따라서 내가 구하려는 인덱스의 문서를 기록할 데이터가 필요하다고 생각했다.
우선 배열의 입력값은 1~9 까지의 양수이기 때문에, 내가 원하는 인덱스의 중요도를 -1로 변경하였다.
그렇게 되면 배열은 내가 원하는 인덱스의 값이 -1인 배열이 된다.
따라서 해당 인덱스의 원래 중요도가 필요하다. ( -1로 변경되었으므로)
이후에 인쇄를 할 때는 중요도가 -1이 들어오면(내가 원하는 인덱스의 중요도), 원래의 중요도와 해당 문서 뒤에 있는 중요도와 비교하고, 인쇄 여부를 결정한다.
priorities = [2,1,3,2]
location = 2
priorValue = 3
priorities = [2,1,-1,2] -> 큐에다 넣음
count = 0
poll = 2
priorValue = 3
priorities = [1,-1,2]
count = 0
priorValue = 3
priorities = [1,-1,2,2]
count = 0
priorValue = 3
priorities = [-1,2,2,1]
count = 0
poll = -1
priorValue = 3
priorities = [2,2,1]
count = 0
count = 1
import java.util.Queue;
import java.util.LinkedList;
class Solution {
// 인쇄 목록에서 가장 중요도가 높은 문서를 먼저 출력
// 가장 앞에 있는 문서의 중요도보다 높은 문서가 있으면 마지막으로 보냄
// 내가 인쇄를 요청한 문서가 몇 번째로 인쇄되는지 출력
public int solution(int[] priorities, int location) {
Queue<Integer> queue = new LinkedList<>();
// 원하는 위치의 값을 -1 로 바꿔서 표시
// -1로 바꾼 값의 원래 값을 priorValue에 저장
int priorValue=priorities[location];
priorities[location]=-1;
for(int i=0;i<priorities.length;i++){
queue.add(priorities[i]);
}
//
// -1 // 1 9 1 1
// 인쇄된 문서의 갯수
int count=0;
//System.out.println(queue.toString());
while(!queue.isEmpty()){
// 맨 앞 종이의 중요도
int first = queue.poll();
//System.out.println("중요도: "+first+" "+queue.toString());
// 원하는 종이가 가장 앞에 왔을 때
if(first==-1){
// 만약 그 종이가 인쇄될 수 있는 순서이면
if(isMax(queue,priorValue,priorValue)){
//System.out.println("출력 완료");
return count+1;
}
// 큐에 중요도가 더 높은 문서가 있으면
else{
// 아직 출력할 수 없음
//System.out.println("중요도 "+first+" 인 문서 맨 뒤로 보냄");
queue.add(-1);
}
}
// 원하는 종이가 아닐 때
else{
// 중요도가 큐에 있는 값 중 가장 크면
if(isMax(queue,first,priorValue)){
// 해당 문서를 인쇄
//System.out.println("중요도 "+first+" 인 문서 인쇄");
count++;
}
// 중요도가 더 큰 문서가 뒤에 있으면
else{
//System.out.println("중요도 "+first+" 인 문서 맨 뒤로 보냄");
queue.add(first);
}
}
}
return count;
}
// poll 된 값이 큐에 있는 중요도 중 제일 높은지 판별하는 메소드
// priorValue( 출력을 원하는 문서의 중요도) 와도 비교가 필요하다. -1로 바꾸어졌기 때문
public boolean isMax(Queue<Integer> queue, int data, int priorValue){
if(data<priorValue){
return false;
}
for(int x : queue){
if(data<x){
return false;
}
}
return true;
}
}