[프로그래머스(Programmers)] 디스크 컨트롤러 (java, 힙/우선순위 큐)

0
post-thumbnail

안녕하세요. 오늘은 프로그래머스의 디스크 컨트롤러 문제를 풀어보겠습니다.!!


문제링크

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

전체 코드

import java.util.*;

public class solution {

    public int solution(int[][] jobs){

        int answer = 0;
        int cnt = 0;
        int time = 0;

        LinkedList<Job> waiting = new LinkedList<>();
        PriorityQueue<Job> pQueue = new PriorityQueue<>(new Comparator<Job>() {
            @Override
            public int compare(Job o1, Job o2) {
                return o1.workingTime - o2.workingTime;
            }
        });

        for (int[] arr : jobs) {
            waiting.offer(new Job(arr[0], arr[1]));
        }

        Collections.sort(waiting, new Comparator<Job>() {
            @Override
            public int compare(Job o1, Job o2) {
                return o1.requestTime - o2.requestTime;
            }
        });

        time = waiting.peek().requestTime;

        while(cnt < jobs.length) {
            while(!waiting.isEmpty() && waiting.peek().requestTime <= time) {
                pQueue.offer(waiting.poll());
            }

            if (!pQueue.isEmpty()) {
                Job job = pQueue.poll();

                time = time + job.workingTime;
                answer = answer+ time - job.requestTime;
                cnt++;
            } else {
                time++;
            }
        }
        return answer/cnt;
    }

}

class Job {
    int requestTime;
    int workingTime;

    Job(int requestTime, int workingTime) {
        this.requestTime = requestTime;
        this.workingTime = workingTime;
    }
}

[참고한 곳]
https://velog.io/@hyeon930/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%EB%94%94%EC%8A%A4%ED%81%AC-%EC%BB%A8%ED%8A%B8%EB%A1%A4%EB%9F%AC-Java

0개의 댓글