[프로그래머스]디스크 컨트롤러(Java)

kjihye0340·2021년 5월 5일
0

programmers

목록 보기
1/3

문제

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

풀이

우선순위 큐를 이용한 문제이다.
우선순위 큐를 각각 시작 시간 순서(PQ)소요 시간 순서(scheduleQ)로 만든다.
시간(time)이 흘러감에 따라, 시작 시간이 time보다 같거나 더 이전일 경우의 job을 PQ에서 scheduleQ로 넣어준다.
그 뒤, scheduleQ에 들어있는 job을 이용해 모든 job의 요청~종료 시간(answer)과 time을 업데이트 해준다.
answer를 다 구하면 평균을 내서 return한다.

코드

import java.util.*;
class Solution {
    
    public int solution(int[][] jobs) {
    
        PriorityQueue<int[]> PQ = new PriorityQueue(new Comparator<int[]>(){
            @Override
            public int compare(int[] a1, int[] a2){
                return Integer.compare(a1[0], a2[0]);
            }
        });
        for(int[] job : jobs){
            PQ.add(job);
        }
        PriorityQueue<int[]> scheduleQ = new PriorityQueue(new Comparator<int[]>(){
            @Override
            public int compare(int[] a1, int[] a2){
                return Integer.compare(a1[1], a2[1]);
            }
        });
        
        int N = PQ.size();
        int time = 0;
        int answer = 0;
        
        while(!PQ.isEmpty() || !scheduleQ.isEmpty()){
            while(!PQ.isEmpty() && time>=PQ.peek()[0]){
                scheduleQ.add(PQ.poll());
            }
            if(scheduleQ.isEmpty()){
                time ++;
                continue;
            }
            if(!scheduleQ.isEmpty()){
                int[] curArr = scheduleQ.poll();
                answer = answer + (time-curArr[0]) + curArr[1];
                time = time + curArr[1];
            }
        }
        answer = answer/N;
        return answer;
    }
}

0개의 댓글