티스토리 뷰

PS/programmers

Level2) 프린터

kingsubin 2020. 10. 9. 18:20
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int solution(int[] priorities, int location) {
        int answer = 0;
        Queue<Printer> q = new LinkedList<>();

        for (int i = 0; i < priorities.length; i++) {
            q.offer(new Printer(i, priorities[i]));
        }

        while (!q.isEmpty()) {
            boolean flag = false;
            int com = q.peek().prior; // 맨 앞
            for (Printer p : q) {
                if (com < p.prior) {
                    flag = true;
                }
            }

            if (flag) {
                q.offer(q.poll());
            } else { // 현재 맨 앞이 가장 큰 수 이면
                if (q.poll().location == location) {
                    answer = priorities.length - q.size();
                }
            }
        }

        return answer;
    }

    class Printer {
        int location;
        int prior;

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

 

- 스택/큐 문제라서 큐를 써야겠다는 생각이 들었고 

  location값을 기준으로 왼쪽 오른쪽으로 큐를 2개 나눠서 해보자 하고 접근했는데 하다 보니 틀린 거 같고 

  더 이상 해결해 나가지 못해서 다른 풀이 찾아봄

- 여러가지 풀이가 있었는데 그나마 이해가 되고 따라갈 수 있는 거를 따라가 보았다.

 

 

1. location과 prior를 같이 가지고 다닐 수 있게 Printer 클래스로 움직임

2. 전체 배열을 queue에 저장

3. q가 빌 때까지 검사 

3-1. 맨 앞의 값을 기준으로 q 전체에 더 큰 값이 있다면 맨 앞의 값을 맨 뒤로 이동

3-2. 맨 앞의 값이 가장 큰 값이면 출력 -> q.poll

3-3. 이때 location이 원하는 정답의 location과 같다면 answer = priorities.length - q.size();

      전체 등수 - 현재 남아있는 printer의 수

 

 

해볼 만할 거 같다고 생각했는데 어렵다....

'PS > programmers' 카테고리의 다른 글

Level2) 다리를 지나는 트럭  (0) 2020.10.11
Level2) 주식가격  (0) 2020.10.09
Level1) 두 개 뽑아서 더하기  (0) 2020.10.08
Level1) x만큼 간격이 있는 n개의 숫자  (0) 2020.09.12
Level1) 하샤드 수  (0) 2020.09.12