프로그래머스 프린터

BbongGu·2023년 4월 17일

Programmers

목록 보기
1/3

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

import java.util.*;
class Solution {
    public int solution(int[] priorities, int location) {
        int[] pr = new int[10];
        Queue<Point> queue = new LinkedList<Point>();
        for(int i=0; i<priorities.length; i++){
            if(i==location) queue.offer(new Point(priorities[i], true));
            else queue.offer(new Point(priorities[i], false));
            pr[priorities[i]]++;
        }
        int answer = 0;
        while(!queue.isEmpty()){
            Point p = queue.poll();
            for(int i=9; i>0; i--){
                if(pr[i]!=0){
                    if(i > p.val) queue.offer(p);
                    else if(i == p.val){
                        if(p.check) return answer+1;
                        else {
                            pr[i]--;
                            answer++;
                        }
                    }
                    break;
                }
            }
        }
        return answer;
    }
    private static class Point {
        int val;
        boolean check;
        public Point(int val, boolean check){
            this.val = val;
            this.check = check;
        }
    }
}

해결

우선 앞에서 부터 빼서 검사를 하기 때문에 Queue를 사용한다.
이 때 중요도와 location을 같이 가지고 가기 위해 class를 생성하였다.
priorities에는 중요도가 1 ~ 9 까지 있기 때문에 pr배열을 만들어 수가 몇 개 가 들어왔는지 확인.
queue에서 하나씩 빼면서 pr배열을 뒤에서부터 확인 했을 때 0이 아닌 수가 있는지 확인한다.(뒤에서 부터 확인했을 때 처음으로 0이 아닌 수가 나온다면 그 때 index가 가장 큰 수이다.)

  • 만약 index가 poll() 한 값보다 크다면 다시 queue에 넣는다.
  • 만약 index와 poll()한 값이 같다면 그 수가 location이랑 같으면 answer+1을 리턴하고 아니라면 pr[index]--와 answer++를 진행한다.
profile
개발새내기

0개의 댓글