Cpp와 조금씩 미묘하게 달라, 적응이 필요하다.
import java.util.LinkedList;
import java.util.Queue;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
Queue<Pair> q = new LinkedList<>();
for (int i = 0; i < priorities.length; i++) {
q.offer(new Pair(i, priorities[i]));
}
while(!q.isEmpty()) {
boolean flag = false;
int prio = q.peek().priority;
for(Pair p : q) {
if(prio < p.priority) {
flag = true;
}
}
if(flag) {
q.offer(q.poll());
answer++;
}
else {
if(q.poll().location == location) return priorities.length - q.size();
}
}
return answer;
}
}
class Pair{
int location;
int priority;
Pair(int location,int priority){
this.location = location;
this.priority = priority;
}
}
class Solution {
public int solution(int[] priorities, int location) {
Queue<Pair> q = new LinkedList<>();
for (int i = 0; i < priorities.length; i++) {
q.offer(new Pair(i, priorities[i]));
}
}
}
class Pair{
int location;
int priority;
Pair(int location,int priority){
this.location = location;
this.priority = priority;
}
}
Pair라는 클래스를 만들어 (location
, priority)
구조로 큐에 담는다.
while(!q.isEmpty()) {
boolean flag = false;
int prio = q.peek().priority; //현재 중요도
for(Pair p : q) {
if(prio < p.priority) { //현재 중요도 보다 높은 중요도가 있을 경우
flag = true;
}
}
if(flag) { //맨앞의 값을 뒤로 옮긴다
q.offer(q.poll());
answer++;
}
else { //맨앞의 값을 없앤다. 만약, 요청한 번호라면 리턴
if(q.poll().location == location) return priorities.length - q.size();
}
}