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 ith 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.
Example 1:
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
Constraints:
tasks.length == n
1 <= n <= 105
1 <= enqueueTimei, processingTimei <= 109
解法1:
这题感觉不容易。我一开始想的是把3个变量(enqueueTime, procTime, index)放到一个Node节点里面,然后用minHeap来做。
后来发现不好处理,因为每次CPU处理一个任务完后,会有一些新的curTime >= enqueueTime的任务变得可行,这个只用minHeap来做是不行的,因为我们不能一个个pop出来检查,再把可以的放回去。
参考的网上的做法。用pair
long long curTime = 0;
class Solution {
public:
vector<int> getOrder(vector<vector<int>>& tasks) {
int n = tasks.size();
//priority_queue, vector>, greater> minHeap; //
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> minHeap; //
vector<pair<int, pair<int, int>>> nodes; // >
vector<int> res;
for (int i = 0; i < n; i++) {
nodes.push_back({tasks[i][0], {tasks[i][1], i}});
}
sort(nodes.begin(), nodes.end());
int index = 0;
while (res.size() < n) {
if (!minHeap.empty()) { //注意这里不能用while,因为每个任务处理完以后,又有一些新的任务可行,这些新的任务可能比当前的top还应该先处理。
auto topNode = minHeap.top();
minHeap.pop();
res.push_back(topNode.second);
curTime += topNode.first;
} else if (index < n) {
curTime = nodes[index].first;
} else break;
for (; index < n; index++) {
if (curTime >= nodes[index].first) {
minHeap.push(nodes[index].second);
} else break;
}
}
return res;
}
};