# 1834. Single-Threaded CPU ###### tags: `Leetcode` `Medium` `Priority Queue` Link: https://leetcode.com/problems/single-threaded-cpu/ ## 思路 $O(NlogN)$ $O(N)$ 首先根据available time排序,然后用一个变量记录curr time,再用while回圈遍历,把每次available time小于curr time的task放到priority queue里面,根据process time和idx的大小关系,每次拿出一个task执行 ## Code ```java= class Task{ int idx; int eTime; int processTime; } class Solution { public int[] getOrder(int[][] tasks) { Task[] t = new Task[tasks.length]; for(int i = 0;i < tasks.length;i++){ t[i] = new Task(); t[i].idx = i; t[i].eTime = tasks[i][0]; t[i].processTime = tasks[i][1]; } Arrays.sort(t, (a, b)->(a.eTime-b.eTime)); Queue<Task> pq = new PriorityQueue<>((a,b)->(a.processTime==b.processTime?a.idx-b.idx:a.processTime-b.processTime)); int[] ans = new int[tasks.length]; int ansIdx = 0; int currTime = 0; int taskIdx = 0; while(ansIdx<tasks.length){ while(taskIdx<tasks.length && t[taskIdx].eTime<=currTime){ pq.offer(t[taskIdx++]); } if(pq.isEmpty()){ currTime = t[taskIdx].eTime; continue; } Task best = pq.poll(); ans[ansIdx++] = best.idx; currTime += best.processTime; } return ans; } } ```