zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    协议
    网页制作
    知识点--------二维数组
    方法---------拖延,清屏,前景色,背景色
    小知识点------遍历数组、switch case、do while
    知识点-----------函数
    循环经典--------冒泡排序,查找。
    知识点-------一维数组
    循环语句-----经典案例
    知识点--循环语句
  • 原文地址:https://www.cnblogs.com/msymm/p/8278232.html
Copyright © 2011-2022 走看看