GaGe

[프로그래머스] 프린터 - java 본문

알고리즘/[2020] 프로그래머스

[프로그래머스] 프린터 - java

Sorrel 2020. 4. 15. 12:41
import java.util.*;
class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 1;
         PriorityQueue<Integer> pri = new PriorityQueue<Integer>(Collections.reverseOrder());

        for(int i : priorities){ //priorities에 있는 원소i를 큐에 넣는다
            pri.add(i);
        }
        while(!pri.isEmpty()){ 
            //아래 for문도 계속 반복됨. priorities가 큐처럼 작용.
            for(int i = 0; i<priorities.length; i++){ //priorities를 하나씩 pri의 peek과 비교
                if(priorities[i]==pri.peek()){
                    if(location==i){
                        return answer; //location이 현재 print 우선순위와 같다면 그 당시의 순서 return
                    }
                    else{//location의 순서가 아닐 경우 다음 비교를 위한 준비작업
                        pri.poll(); //우선순위 비교 대상을 다음으로 넘김
                        answer++; //순서 +1
                    }
                }
            }
        }
        return answer;
    }
}

Queue sort를 찾다가 PriorityQueue를 새롭게 알게 됨. 참 유용하다.

Collentions.reverseOrder()를 이용하면 내림차순으로 priority 정렬!

이용하지 않으면 올림차순으로 priority 정렬!

Comments