程式語言 - LeetCode - CPP - 621. Task Scheduler



參考資訊:
https://www.cnblogs.com/grandyang/p/7098764.html

題目:


方法:

沒用 priority_queue 的結果:idle 會增加

解答:

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        unordered_map<char, int> mp;

        for (char c : tasks) {
            mp[c] += 1;
        }

        priority_queue<int> q;

        for (auto& [k, v] : mp) {
            q.push(v);
        }

        int ans = 0;

        while (!q.empty()) {
            int cnt = 0;
            vector<int> t;

            for (int i = 0; i < n + 1; ++i) {
                if (!q.empty()) {
                    int n = q.top();

                    q.pop();

                    n -= 1;
                    if (n > 0) {
                        t.push_back(n);
                    }
                    cnt += 1;
                }
            }

            for (int n : t) {
                q.push(n);
            }

            ans += q.empty() ? cnt : n + 1;
        }

        return ans;
    }
};