| 1 | class Solution { |
| 2 | public int[] getOrder(int[][] tasks) { |
| 3 | |
| 4 | // Sort based on min task processing time or min task index. |
| 5 | PriorityQueue<int[]> nextTask = new PriorityQueue<int[]>((a, b) -> (a[1] != b[1] ? (a[1] - b[1]) : (a[2] - b[2]))); |
| 6 | |
| 7 | // Store task enqueue time, processing time, index. |
| 8 | int sortedTasks[][] = new int[tasks.length][3]; |
| 9 | for (int i = 0; i < tasks.length; ++i) { |
| 10 | sortedTasks[i][0] = tasks[i][0]; |
| 11 | sortedTasks[i][1] = tasks[i][1]; |
| 12 | sortedTasks[i][2] = i; |
| 13 | } |
| 14 | |
| 15 | // Sort the tasks based on enqueueTime |
| 16 | Arrays.sort(sortedTasks, (a, b) -> Integer.compare(a[0], b[0])); |
| 17 | int tasksProcessingOrder[] = new int[tasks.length]; |
| 18 | |
| 19 | long currTime = 0; |
| 20 | int taskIndex = 0; |
| 21 | int ansIndex = 0; |
| 22 | |
| 23 | // Stop when no tasks are left in array and heap. |
| 24 | while (taskIndex < tasks.length || !nextTask.isEmpty()) { |
| 25 | if (nextTask.isEmpty() && currTime < sortedTasks[taskIndex][0]) { |
| 26 | // When the heap is empty, try updating currTime to next task's enqueue time. |
| 27 | currTime = sortedTasks[taskIndex][0]; |
| 28 | } |
| 29 | |
| 30 | // Push all the tasks whose enqueueTime <= currtTime into the heap. |
| 31 | while (taskIndex < tasks.length && currTime >= sortedTasks[taskIndex][0]) { |
| 32 | nextTask.add(sortedTasks[taskIndex]); |
| 33 | ++taskIndex; |
| 34 | } |
| 35 | |
| 36 | int[] temp = nextTask.poll(); |
| 37 | |
| 38 | // Complete this task and increment currTime. |
| 39 | currTime += temp[1]; |
| 40 | tasksProcessingOrder[ansIndex++] = temp[2]; |
| 41 | } |
| 42 | |
| 43 | return tasksProcessingOrder; |
| 44 | } |
| 45 | } |