[프로그래머스] 42587번 : 프린터

이도은·2022년 1월 16일
1


코드

import java.util.Collections;
import java.util.PriorityQueue;

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

        PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

        for (int i = 0; i < priorities.length; i++) {
            pq.add(priorities[i]);
        }

        while (!pq.isEmpty()) {

            for (int i = 0; i < priorities.length; i++) {

                // 우선순위 큐의 첫번째 값과 우선순위 배열[i]의 값이 같다면
                if (priorities[i] == pq.peek()) {

                    // 심지어, 찾고자 하는 위치와 인덱스인 i가 같다면
                    if (i == location) {

                        //정답을 +1 증가해주고 바로 리턴.
                        answer++;
                        return answer;
                    }

                    // 찾고자 하는 위치가 아니기 때문에 우선순위 큐의 첫번째 값을 제거.
                    pq.poll();
                    // 정답을 +1 증가해주고 다음 우선순위 배열의 값으로 반복.
                    answer++;
                }
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        int[] priorities = {2, 1, 3, 2};
        int location = 2;

        System.out.println(solution(priorities, location));
    }
}

풀이 및 느낀점


참고자료

0개의 댓글