621. Task Scheduler

Description:

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example 1:

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].


簡要題解:

採用貪心算法。

核心思想是: 每次挑選能執行的並且剩餘最多的那種task來執行。沒有這樣的task時,就反覆添加idle直到有可以執行的task。重複前面的步驟。

另外,要注意到,不需要詳細地區分task的類型,只要能知道每種task剩下的數量即可。


代碼:

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        vector<int> taskStats(26, 0);
        int num = 0, i;

        for (int i = 0; i < tasks.size(); i++)
            taskStats[int(tasks[i]-'A')]++;

        sort(taskStats.begin(), taskStats.end());
        while (true) {
            for (i = taskStats.size() - 1; i >= 0 && taskStats[i] != 0; i--) {
                taskStats[i]--;
                if (taskStats.size() - 1 - i == n) {
                    i--;
                    break;
                }
            }

            sort(taskStats.begin(), taskStats.end());
            if (taskStats.back() != 0) {
                num += 1 + n;
            } else {
                num += taskStats.size() - 1 - i;
                break;
            }
        }

        return num;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章