알고리즘 풀이/프로그래머스

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

배게 2019. 12. 4. 11:55
728x90

테케 8,18 fail 했었음.


맨처음 Arrays.sort할 때 


작업 요청시간을 기준으로만 정렬해줫는데


작업요청시간이 동일한 경우에도 정렬을 해줘야 하는 것을 간과했음. 


작업요청시간이 동일한 작업들은 작업소요시간을 기준으로 오름차순으로 정렬해줘야함


그나마 저번에 한번 풀어봐서 스스로 풀긴함



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
    public int solution(int[][] jobs) {
        int answer = 0;
 
        Arrays.sort(jobs, new Comparator<int[]>() {
            @Override
            public int compare(int[] j1, int[] j2) {
                if (j1[0< j2[0])
                    return -1;
                else if (j1[0== j2[0]) {
                    if (j1[1< j2[1])
                        return -1;
                }
                return 1;
            }
        });
 
        // for(int i=0; i<jobs.length; i++){
        //     System.out.println(jobs[i][0]+" "+jobs[i][1]);
        // }
 
        PriorityQueue<Job> waitList = new PriorityQueue<>();
        Queue<Job> q = new LinkedList<>();
 
        for (int i = 0; i < jobs.length; i++) {
            q.add(new Job(jobs[i][0], jobs[i][1]));
        }
 
        // System.out.println();
        // while(!q.isEmpty()){
        //     System.out.println(q.poll());
        // }
 
        if (jobs.length == 1)
            return jobs[0][1];
 
        int time = 0;
        Job now = null;
 
        while (true) {
            if (now == null) {
                if (waitList.isEmpty()) {
                    now = q.poll();
                    time = now.start;
                } else {
                    now = waitList.poll();
                }
            } else {
                time += now.workTime;
                answer += (time - now.start);
                now = null;
 
                while (!q.isEmpty() && q.peek().start <= time) {
                    waitList.add(q.poll());
                }
 
            }
 
            if (waitList.isEmpty() && q.isEmpty() && now == null)
                break;
        }
 
        answer /= jobs.length;
 
        return answer;
    }
 
    class Job implements Comparable<Job> {
        int start;
        int workTime;
 
        Job(int start, int workTime) {
            this.start = start;
            this.workTime = workTime;
        }
 
        @Override
        public int compareTo(Job j) {
            return Integer.compare(this.workTime, j.workTime);
        }
 
        public String toString() {
            return this.start + " " + this.workTime;
        }
 
    }
cs