본문 바로가기
정리/알고리즘

힙(Heap)-디스크 컨트롤러

by Hudini30 2022. 2. 10.

프로그래머스(힙)- 디스크 컨트롤러

해당 문제는 2개의 우선순위 큐를 이용하여 풀었습니다. 하나는 접수시간을 기준으로 하는 큐 jobInfoQueue, 하나는 작업시간을 기준으로 하는 waitingQueue를 두었습니다. 한번에 하나의 작업밖에 진행 할 수 없고, 전체 작업시간은 어떤 순서로 진행하든 동일 하기 때문에 endTime을 미리 계산 한 후 현재 시간이 endTime 보다 작을때까지 반복문을 수행하게 합니다. 접수대기중인 잡의 정보를 가진 jobInfoQueue에서 peek 값을 확인하여 접수시간이 현재시간 보다 작은 잡의 정보를 전부 wattingQueue에 집어 넣은 후, 제일 작업시간이 짧은 잡의 정보를 꺼내 잡을 수행하게 합니다. 이후 작업시간 만큼은 어떠한 잡도 수행하지 못하기 때문에 현재시간을 작업시간 이 후의 시간으로 세팅하여 위의 반복문을 다시 반복하게 함으로써 해당 문제를 풀었습니다.

public int solution(int[][] jobs) {
        Queue<JobInfo> jobInfoQueue = new PriorityQueue<>(Comparator.comparingInt(JobInfo::getAcceptTime));
        Queue<JobInfo> waitingQueue = new PriorityQueue<>(Comparator.comparingInt(JobInfo::getJobProcessTime));

        int endTime = 0;

        for (int[] job : jobs) {
            jobInfoQueue.add(new JobInfo(job[0], job[1]));
            endTime += job[1];
        }

        int totalWaitingTime = 0;
        int time = jobInfoQueue.peek().getAcceptTime();

        while (time < endTime) {
            while (!jobInfoQueue.isEmpty() && jobInfoQueue.peek().getAcceptTime() <= time) {
                waitingQueue.add(jobInfoQueue.poll());
            }

            if (!waitingQueue.isEmpty()) {
                JobInfo jobInfo = waitingQueue.poll();
                time = time + jobInfo.getJobProcessTime();
                totalWaitingTime += time - jobInfo.getAcceptTime();
            } else {
                time++;
            }
        }

        return totalWaitingTime / jobs.length;
    }

'정리 > 알고리즘' 카테고리의 다른 글

정렬-가장 큰 수  (0) 2022.02.15
정렬-K번째 수  (0) 2022.02.14
힙(Heap) 더맵게  (0) 2022.02.09
스택/큐 - 주식가격  (0) 2022.02.08
스택/큐 - 다리를 지나는 트럭  (0) 2022.02.07

댓글