프로그래머스 코딩테스트 연습/Level3
[프로그래머스][JAVA] 디스크 컨트롤러
긷뚜
2021. 5. 5. 12:42
728x90
programmers.co.kr/learn/courses/30/lessons/42627
코딩테스트 연습 - 디스크 컨트롤러
하드디스크는 한 번에 하나의 작업만 수행할 수 있습니다. 디스크 컨트롤러를 구현하는 방법은 여러 가지가 있습니다. 가장 일반적인 방법은 요청이 들어온 순서대로 처리하는 것입니다. 예를
programmers.co.kr
PriorityQueue를 이용해 푼 문제이다
만약 queue가 비어있다면 다음 작업을 수행하는 사이에 들어오는 요청들을 소요시간 기준으로 오름차순 정렬하여
종료시간 - 요청시간을 더하는 식으로 구현하였다
주의할점은 하나의 작업이 끝나고 다음작업을 할때마다 작업중 에 들어오는 요청은 모두 PriorityQueue를 통해 정렬
해야한다.
import java.util.*;
class Solution {
public int solution(int[][] jobs) {
int answer = 0;
int timeCount = 0; //흐른시간
int count = 0;
int jobsIndex = 0;
Arrays.sort(jobs, new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2){
Integer a = o1[0];
Integer b = o2[0];
return a.compareTo(b);
}
});
PriorityQueue<Disk> pQ = new PriorityQueue<>();
while(count<jobs.length){
while(jobsIndex<jobs.length&&jobs[jobsIndex][0]<=timeCount){
pQ.offer(new Disk(jobs[jobsIndex][0],jobs[jobsIndex][1]));
jobsIndex++;
}
if(pQ.isEmpty()){
timeCount = jobs[jobsIndex][0];
}
else{
int request = pQ.peek().index;
int finish = pQ.poll().time;
answer += finish + timeCount - request;
timeCount += finish;
count++;
}
}
return answer/jobs.length;
}
private static class Disk implements Comparable<Disk> {
int index;
int time;
Disk(int index, int time) {
this.index = index;
this.time = time;
}
@Override
public int compareTo(Disk o) {
return this.time - o.time;
}
}
}
728x90