[프로그래머스] 프린터 (java)

HaYeong Jang·2021년 3월 28일
0
post-thumbnail

🔗 문제링크

https://programmers.co.kr/learn/courses/30/lessons/42587

👩🏻‍💻 코드

import java.util.*;

class Printer {
    int location;
    int priority;

    Printer(int location, int priority) {
        this.location = location;
        this.priority = priority;
    }
}

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

        Queue<Printer> queue = new LinkedList<>();
        for (int i = 0; i < priorities.length; i++) {
            queue.add(new Printer(i, priorities[i]));
        }

        while (!queue.isEmpty()) {
            boolean flag = false;
            Printer cur = queue.peek();

            for (Printer q : queue) {
                if (cur.priority < q.priority) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {    // 우선순위가 가장 높은 경우
                if (queue.poll().location == location) {
                    answer = priorities.length - queue.size();
                    break;
                }
            } else {
                queue.add(queue.poll());
            }
        }
        return answer;
    }
}

📝 정리

현재 프린터의 우선순위가 뒤에 오는 것들보다 높은지 flag로 구분해 줬다.
flag가 true 면 큐에 맨 뒤에 추가하고, false 면 queue에서 뽑아줬다.
그리고 구하려는 프린터의 location과 같을 경우 answer로 대입해 줬다.

profile
기억하기 위해 기록하는 개발로그👣

0개의 댓글