6 Oct 2020

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


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

프로그래머스


Shortest Job First(SJF)

waitQueue : 들어온 요청이 기다리는 큐
    - startTime 오름차순 -> 작업이 요청되는 순서대로 정렬
workQueue : 수행될 작업이 있는 큐
    - 작업 시간이 짧은 순으로 정렬
currentTime : 현재시간

1. 먼저 요청이 들어온 순서대로 waitQueue에 넣는다.

2. waitQueue에서 currentTime 이전에 들어온 요청들을 workQueue에 삽입

3. workQueue에 작업이 있다면 currentTime, 요청~종료 시간 answer 값 갱신

### 3-1. workQueue에 작업이 없다면 currentTime 1씩 증가 ### 4. 최종 answer을 전체 작업으로 나눈 평균값 도출
import java.util.*;
class Solution {
    class Job{
        int startTime;
        int workTime;
        Job(int startTime,int workTime){
            this.startTime=startTime;
            this.workTime=workTime;
        }
    }
    public int solution(int[][] jobs) {
        LinkedList<Job> waitQueue=new LinkedList<>();
        PriorityQueue<Job> workQueue=new PriorityQueue<>((a,b)->{
            return a.workTime>b.workTime ? 1:(a.workTime==b.workTime ? 0 : -1);
        });
        int cnt=0;
        int answer = 0;
        int currentTime=0;
        int len=jobs.length;
        for(int i=0;i<len;i++){
            waitQueue.add(new Job(jobs[i][0],jobs[i][1]));
        }
        waitQueue.sort((a,b)->{
            return a.startTime>b.startTime ? 1:(a.startTime==b.startTime ? 0 : -1);
        });
        
        while(cnt<len){
            //waitQueue(대기하고 있는 작업이 있는 큐) -> workQueue(작업들이 대기하는 큐)
            while(!waitQueue.isEmpty()&&waitQueue.peek().startTime<=currentTime){
                workQueue.offer(waitQueue.pollFirst());
            }
            if(!workQueue.isEmpty()){
                Job job=workQueue.poll();
                currentTime+=job.workTime;
                answer+=currentTime-job.startTime;
                cnt++;
            }else{
                currentTime++;
            }
        }
        answer/=cnt;
        return answer;
    }
}


Tags:
0 comments