1834. Single-Threaded CPU
Problem
tasks[i] = [enqueueTime, processingTime]. A single-threaded CPU, whenever idle, starts the available task with the shortest processing time (ties: smallest index) and runs it to completion; if nothing is available it waits. Return the order in which the tasks are processed.
Example: [[1,2],[2,4],[3,2],[4,1]] → [0,2,3,1]
Constraints: up to 10⁵ tasks.
Sort tasks by enqueue time. At each step, push all tasks that have arrived by time into a heap keyed by (processing time, index); run the top. If the heap is empty, jump time to the next arrival.
Complexity: O(n log n).
class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
order = sorted(range(len(tasks)), key=lambda i: tasks[i][0])
h, res, time, i = [], [], 0, 0
while len(res) < len(tasks):
if not h and time < tasks[order[i]][0]:
time = tasks[order[i]][0]
while i < len(order) and tasks[order[i]][0] <= time:
j = order[i]
heappush(h, (tasks[j][1], j))
i += 1
p, j = heappop(h)
time += p
res.append(j)
return res
assert Solution().getOrder([[1, 2], [2, 4], [3, 2], [4, 1]]) == [0, 2, 3, 1]
assert Solution().getOrder([[7, 10], [7, 12], [7, 5], [7, 4], [7, 2]]) == [4, 3, 2, 0, 1]
class Solution {
public int[] getOrder(int[][] tasks) {
int n = tasks.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> tasks[a][0] - tasks[b][0]);
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> tasks[a][1] != tasks[b][1] ? tasks[a][1] - tasks[b][1] : a - b);
int[] res = new int[n];
long time = 0;
for (int k = 0, i = 0; k < n; k++) {
if (pq.isEmpty() && time < tasks[order[i]][0]) time = tasks[order[i]][0];
while (i < n && tasks[order[i]][0] <= time) pq.add(order[i++]);
int j = pq.poll();
time += tasks[j][1];
res[k] = j;
}
return res;
}
}
type job struct{ proc, idx int }
type jobHeap []job // shortest processing time, then smallest index
func (h jobHeap) Len() int { return len(h) }
func (h jobHeap) Less(i, j int) bool {
if h[i].proc != h[j].proc {
return h[i].proc < h[j].proc
}
return h[i].idx < h[j].idx
}
func (h jobHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *jobHeap) Push(x any) { *h = append(*h, x.(job)) }
func (h *jobHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func getOrder(tasks [][]int) []int {
order := make([]int, len(tasks))
for i := range order {
order[i] = i
}
sort.Slice(order, func(a, b int) bool { return tasks[order[a]][0] < tasks[order[b]][0] })
h, res, time, i := &jobHeap{}, []int{}, 0, 0
for len(res) < len(tasks) {
if h.Len() == 0 && time < tasks[order[i]][0] { // idle until the next task arrives
time = tasks[order[i]][0]
}
for i < len(order) && tasks[order[i]][0] <= time {
heap.Push(h, job{tasks[order[i]][1], order[i]})
i++
}
j := heap.Pop(h).(job)
time += j.proc
res = append(res, j.idx)
}
return res
}