|
| 1 | +import java.util.PriorityQueue; |
| 2 | + |
| 3 | +// https://leetcode.com/contest/weekly-contest-237/problems/single-threaded-cpu/ |
| 4 | + |
| 5 | +public class SingleThreadedCPU { |
| 6 | + |
| 7 | + // O(n*log(n)) |
| 8 | + public int[] getOrder(int[][] tasks) { |
| 9 | + // Sort by enqueue time then by processing time |
| 10 | + PriorityQueue<int[]> taskQueue = new PriorityQueue<>( |
| 11 | + (a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); |
| 12 | + |
| 13 | + // Sort by processing time then by id |
| 14 | + PriorityQueue<int[]> waitQueue = new PriorityQueue<>( |
| 15 | + (a, b) -> a[1] == b[1] ? a[2] - b[2] : a[1] - b[1]); |
| 16 | + |
| 17 | + for (int i = 0; i < tasks.length; i++) { |
| 18 | + taskQueue.offer(new int[]{tasks[i][0], tasks[i][1], i}); |
| 19 | + } |
| 20 | + |
| 21 | + int[] result = new int[tasks.length]; |
| 22 | + int finishedTime = -1; |
| 23 | + int idx = 0; |
| 24 | + |
| 25 | + while (!taskQueue.isEmpty() || !waitQueue.isEmpty()) { |
| 26 | + while (!taskQueue.isEmpty() && taskQueue.peek()[0] <= finishedTime) { |
| 27 | + waitQueue.offer(taskQueue.poll()); |
| 28 | + } |
| 29 | + int[] task; |
| 30 | + if (!waitQueue.isEmpty()) { |
| 31 | + task = waitQueue.poll(); |
| 32 | + finishedTime += task[1]; |
| 33 | + } else { // taskQueue is empty |
| 34 | + task = taskQueue.poll(); |
| 35 | + finishedTime = task[0] + task[1]; |
| 36 | + } |
| 37 | + result[idx++] = task[2]; |
| 38 | + } |
| 39 | + return result; |
| 40 | + } |
| 41 | +} |
0 commit comments