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;
        }
    };
  • 相关阅读:
    如何在Windows下安装sass和compass
    HTTP 请求头中的 X-Forwarded-For
    HTTP 代理原理及实现
    node.js使用经验记录
    完美方案——iOS的WebView自适应内容高度
    购物车商品加减效果
    C++17新特性
    栈实现迷宫求解(c++版)
    二叉树遍历及实现
    经典乱码“烫烫烫”和“屯屯屯”
  • 原文地址:https://www.cnblogs.com/msymm/p/8278232.html
Copyright © 2011-2022 走看看