Skip to content
Rain Hu's Workspace
Go back

1834

Rain Hu

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:

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Heap (Priority Queue)

vector<int> getOrder(vector<vector<int>>& tasks) {
    auto comp = [](const auto& a, const auto& b){return a.first == b.first ? a.second > b.second : a.first > b.first;};
    priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(comp)> pq(comp);  // min heap
    long long int timestamp = 0;
    int n = tasks.size();
    vector<int> res; 
    for (int i = 0; i < tasks.size(); i++) {
        tasks[i].push_back(i);      // 標記索引值
    }
    sort(tasks.begin(), tasks.end());   // 排序
    int i = 0;
    while (res.size() < n) {
        if (pq.empty()) {               // 閒置時,時間標籤移動到佇列最前面的任務
            timestamp = tasks[i][0];
        } else {                        // 非閒置時,將時間標籤移動到任務結束時
            auto top = pq.top();
            timestamp += top.first;
            res.push_back(top.second);
            pq.pop();
        }
        while (i < n && tasks[i][0] <= timestamp) { // 加入所有比時間標籤早的任務
            pq.push({tasks[i][1], tasks[i][2]});    // 以 {processingTime, index} 的方式加入 min heap
            i++;
        }
    }   
    return res;
}

回目錄 Catalog


Share this post on:

Previous
string
Next
2463