[Leetcode 621] Task Scheduler

  • Question
    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:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].

  • 解题思路
    这个题有三种情况:

    • n==0 return tasks.size();

    • n>= task 的种类(A:表示一种task, B:表示一种task, 做多26种)。这种情况会有空闲产生。
      例如:
      [A , A, B, B],n=2时, 最省时排列为: A -> B -> idle -> A ->B.

    • n>0 && n < task 的种类。
      先从数量最多的开始取, 以此类推,保证把所有间隔利用起来。由于每类task的数量不等,有些task取完之后就没有了,task 种类减少,可能就会变成第二种情况。
      例如:
      [A , A, B, B, C],n=2 时,最省时排列为: A -> B -> C -> A ->B.
      如果 把C排在前面必然会产生间隔,导致更多的时间。
  • 代码如下:

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值