상세 컨텐츠

본문 제목

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

💯ProblemSolving/문제 풀이-Java

by :부셔져버린개발자 2025. 2. 4. 18:11

본문

       문제 요약        

- 문제

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

 

 

         아이디어        

시간에 대한 처리?

 

 

         소스코드        

import java.util.*;
class Solution {
    static int JOB_SIZE;
    public int solution(int[][] jobs) { // 요청_시각 작업_소요_시간
        JOB_SIZE = jobs.length;
        List<Item> arr = new ArrayList<>();
        for(int i = 0; i < jobs.length; i++) {
            arr.add(new Item(i, jobs[i][0], jobs[i][1]));
        }
        Collections.sort(arr, Comparator.comparingInt(x -> x.reqTime)); // 요청 빨리 온 순서대로 
        
        PriorityQueue<Item> pq = new PriorityQueue<>();
        int jIdx = 0; // 현재까지 요청된 작업 ID
        int curTime = 0;
        int sumReturnTime = 0;
        
        int finishedCnt = 0;
        while(true) {
            if(finishedCnt == JOB_SIZE)break;
            while(jIdx < JOB_SIZE && arr.get(jIdx).reqTime <= curTime) { // 이전 작업 처리 중 요청된 작업 대기 큐에 넣음
                pq.add(arr.get(jIdx));
                jIdx++;
            }
      
            if(!pq.isEmpty()){ // 이전 작업 처리 중 요청된 작업이 있는 경우
                Item cur = pq.poll();
                int returnTime = cur.cost + curTime - cur.reqTime ;
                sumReturnTime += returnTime;
                curTime += cur.cost; // 처리 완료 시점으로 시간 옮김
                finishedCnt += 1; // 처리 완료된 작업 개수 1증가 
            }else { // 이전 작업 처리 중 요청된 작업이 없는 경우 
                curTime += 1; // 다른 작업 요청 시점으로 갱신
            }
        }
        return sumReturnTime/JOB_SIZE;
    }
    static class Item implements Comparable<Item>{
        int id;
        int reqTime;
        int cost;
        Item(int id, int reqTime, int cost) {
            this.id = id;
            this.reqTime = reqTime;
            this.cost = cost;
        }
        @Override
         public int compareTo(Item o) { 
             if (this.cost == o.cost) {
                 if (this.reqTime == o.reqTime) {
                    return this.id - o.id;                     
                 }
                 return this.reqTime - o.reqTime;
             }
             return this.cost - o.cost;
         }
        
        @Override
        public String toString() {
            return this.id +" "+ this.reqTime+" "+ this.cost;
        }
    }
}

 

 

728x90

관련글 더보기