leetcode練習 Task Scheduler

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.

Example1:

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

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

這是一個很巧妙的題。做這道題的是誰是和同學一起在思考,最初的想法是,尋找可以去做的任務中,剩餘最多的那項,代碼比較繁瑣,後來思考之後找到一種簡單的方法:

通常情況下,可以使用最多的那項任務安排的最密集的方式完成,將其他任務填充在之間的空閒,即是這種情況的最優解,其他情況下,剩餘的任務有多的,空閒不夠填充,就會填在後面。這個時候沒有空閒,長度就是任務的長度。代碼如下

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        map<char,int>mp;
        int count = 0;
        for(auto e : tasks)
        {
            mp[e]++;
            count = max(count, mp[e]);
        }

        int ans = (count-1)*(n+1);
        for(auto e : mp) if(e.second == count) ans++;
        return max((int)tasks.size(), ans);
    }
};

簡潔明瞭,巧妙,很不錯的題目。

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