int[] order =newint[n];int orderIdx =0;int runIdx =0;int curTime =0;while (orderIdx < n) {while (runIdx < n && jobs[runIdx].enqueueTime<= curTime) {queue.offer(jobs[runIdx]); runIdx++; }// when no data in queue, curTime needs to refreshif (queue.isEmpty()) { curTime = jobs[runIdx].enqueueTime; } else {Task cur =queue.poll(); order[orderIdx++] =cur.index; curTime +=cur.processingTime; } }return order;
T: O(nlogn)
S: O(n)
classSolution {classTask {int index;int enqueueTime;int processingTime;Task(int index,int enqueueTime,int processingTime) {this.index= index;this.enqueueTime= enqueueTime;this.processingTime= processingTime; } }publicint[] getOrder(int[][] tasks) {int n =tasks.length;Task[] jobs =newTask[n]; for (int i =0; i < n; i++) { jobs[i] =newTask(i, tasks[i][0], tasks[i][1]); }Arrays.sort(jobs, (a,b) ->a.enqueueTime-b.enqueueTime);Queue<Task> queue =newPriorityQueue<>((a,b) -> {returna.processingTime==b.processingTime?a.index-b.index:a.processingTime-b.processingTime; });int[] order =newint[n];int orderIdx =0;int runIdx =0;int curTime =0;while (orderIdx < n) {while (runIdx < n && jobs[runIdx].enqueueTime<= curTime) {queue.offer(jobs[runIdx]); runIdx++; }// when no data in queue, curTime needs to refreshif (queue.isEmpty()) { curTime = jobs[runIdx].enqueueTime; } else {Task cur =queue.poll(); order[orderIdx++] =cur.index; curTime +=cur.processingTime; } }return order; }}/*tasks[i] = [enqueueTimei, processingTimei]ith taskprocess at enqueueTimei, needs processingTimeithe CPU will choose the one with the shortest processing time. => pq (small processingTimei, smallest index)finished entire taskReturn the order in which the CPU will process the tasks. (index)[[1,2],[2,4],[3,2],[4,1]]1. build task class2. define pqcurTime = 0;3. while (orderId < n) { while (runId < n && eTime <= curTime) { add to heap runId++ } if (heap is empty) { init curTime = task[runId].eTime } heap pop, get cur task add to result[orderId++] curTime += cur task.proTime}T: O(nlogn)S: O(n)*/