Greedy- 621. Task Scheduler

Posted 抒抒说

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Greedy- 621. 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.

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].

 

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        int ret=0;
        if(n==0 || tasks.size()<2) return tasks.size();
        vector<int> cnt(26,0);  // A~Z
        for(auto a:tasks)   //统计 每种task的数量
            ++cnt[a-A];
        while(1){
        //[](int a, int b){return a>b;} 是个lambda表达式, 让排序结果为降序排列
            sort(cnt.begin(),cnt.end(),
            [](int a, int b){return a>b;});
            if( n>25 || cnt[n]==0)  //是否为第二种情况
                break;
            ret+=(n+1);
            for(size_t i=0; i<n+1; ++i)
                --cnt[i];
        }
        //第二种情况的计算
        if(cnt[0]!=0){
            ret+=(cnt[0]-1)*(n+1);  // 要减1,见第二种情况示例
            for(int i=0; i<26;++i)
                if(cnt[i]==cnt[0]) ++ret;
        }
        return ret;
    }
};

 

以上是关于Greedy- 621. Task Scheduler的主要内容,如果未能解决你的问题,请参考以下文章

621. Task Scheduler

[LeetCode 621] Task Scheduler

[LeetCode 621] Task Scheduler

621. Task Scheduler

621. Task Scheduler

621. Task Scheduler