[프로그래머스/Level2] 프린터(Java)

SeokHyun·2022년 6월 29일
0

프로그래머스

목록 보기
7/32

문제 링크: https://programmers.co.kr/learn/courses/30/lessons/42587

문제 접근

  1. 인덱스와 우선순위를 저장할 수 있는 클래스 생성

  2. 큐에 인덱스와 우선순위 저장

  3. 제일 앞 원소를 꺼내고, 나머지 원소들 중 꺼낸 원소보다 높은 우선 순위가 있는지 검사

  4. 없으면 출력한 수 증가

  5. 있으면 큐에 다시 넣고 1번부터 반복

소스 코드

import java.util.Queue;
import java.util.LinkedList;

class Solution {
    
    public class Job {
        
        public Job() {
            
        }
        
        public Job(int index, int priority) {
            this.index = index;
            this.priority = priority;
        }
        
        public int index;
        public int priority;
    }
    
    public int solution(int[] priorities, int location) {
        Queue<Job> q = new LinkedList<>();
        
        for (int i = 0; i < priorities.length; i++) {
            q.add(new Job(i, priorities[i]));
        }
        
        int count = 0;
        while (!q.isEmpty()) {
            Job job = q.poll();
            if (isHigherPriority(q, job)) {
                q.add(job);
            } else {
                count++;
                
                if (job.index == location) {
                    return count;
                }
            }
        }
        
        return -1;
    }
    
    public boolean isHigherPriority(Queue<Job> q, Job curJob) {
        for (Job job : q) {
            if (job.priority > curJob.priority) {
                return true;
            }
        }
        
        return false;
    }
}
profile
SI를 넘어 백엔드 엔지니어를 향하여

0개의 댓글