[LeetCode] Single-Threaded CPU

1834. Single-Threaded CPU

You are given n​​​​​​ tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the i​​​​​​th​​​​ task will be available to process at enqueueTimei and will take processingTimei to finish processing.

You have a single-threaded CPU that can process at most one task at a time and will act in the following way:

  • If the CPU is idle and there are no available tasks to process, the CPU remains idle.
  • If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
  • Once a task is started, the CPU will process the entire task without stopping.
  • The CPU can finish a task then start a new one instantly.

Return the order in which the CPU will process the tasks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
vector<int> getOrder(vector<vector<int>>& tasks) {
int idx = 0, sz = tasks.size();
multimap<int, pair<int, int>> mm;
for(int i = 0; i < sz; i++) {
mm.insert({tasks[i].front(), {tasks[i].back(),i}});
}
auto it = mm.begin();
priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int,int>>> pq;
vector<int> res(sz);
for(int time = 0; it != mm.end();) {
while(it != mm.end() && it->first <= time) {
pq.push(it->second);
it++;
}

if(!pq.empty()) {
res[idx++] = pq.top().second;
time = time + pq.top().first;
pq.pop();
} else if(it != mm.end()){
time = it->first;
}
}
while(!pq.empty()) {
res[idx++] = pq.top().second;
pq.pop();
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/18/PS/LeetCode/single-threaded-cpu/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.