몇번째로 인쇄되는지 순서가 중요하고 기본적으로 같은 우선순위일땐 앞의 문서가 먼저 출력되므로 큐를 이용해야 합니다.
int answer = 0;
int print = priorities[location];
boolean is_print;
Queue<Integer> queue = new LinkedList<>();
for(int i=0;i<priorities.length;i++){
queue.add(priorities[i]);
}
프린트 하고자 하는 문서의 위치와 큐를 초기화 합니다.
맨앞에 있는 문서가 가장큰 우선순위를 가지면 인쇄합니다.
int max = it.next(); //맨앞 최대로 가정
while(it.hasNext()){
int temp = it.next();
if(max < temp){ //최대가 아니면
max = temp;
is_print=false; //인쇄x
}
}
맨앞의 문서가 인쇄가 되었는지, 맨뒤로 이동했는지, 찾는 문서가 맨앞이었는지 여부를 확인하며 조정합니다.
int first = queue.poll(); //맨 앞고
location--; //위치 -1
if(is_print){ //최대값이면
answer++; //출력 +1
if(first == print && location == -1) //출력값이고 위치가 0이면(인쇄하고자 하는 값이면)
break;
}else{ //최대값이 아니면
queue.add(first); //맨뒤에 추가
if(location == -1) //뽑고자하는 값이면
location = queue.size()-1; //위치 맨뒤로 해줌
}
}
import java.util.*;
import java.util.stream.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
int print = priorities[location];
boolean is_print;
Queue<Integer> queue = Arrays.stream(priorities).boxed().collect(Collectors.toCollection(LinkedList::new));
while(true){
Iterator<Integer> it = queue.iterator();
is_print = true;
int max = it.next(); //맨앞 최대로 가정
while(it.hasNext()){
int temp = it.next();
if(max < temp){ //최대가 아니면
max = temp;
is_print=false; //인쇄x
}
}
int first = queue.poll(); //맨 앞고
location--; //위치 -1
if(is_print){ //최대값이면
answer++; //출력 +1
if(first == print && location == -1) //출력값이고 위치가 0이면(인쇄하고자 하는 값이면)
break;
}else{ //최대값이 아니면
queue.add(first); //맨뒤에 추가
if(location == -1) //뽑고자하는 값이면
location = queue.size()-1; //위치 맨뒤로 해줌
}
}
return answer;
}
}