LintCode 945: Task Scheduler

  1. Task Scheduler
    中文English
    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
Example1

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

Input: tasks = [‘A’,‘A’,‘A’,‘B’,‘B’,‘B’], n = 1
Output: 6
Explanation:
A -> B -> A -> B -> A -> B.
Notice
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].

解法1:
以tasks=“AAABBBC”, n=2为例。因为每个同名task之间要隔开n,所以可以将tasks分成若干个间隔。假设最多的task有max个intervals,共有numOfMaxTask个task并列最多(这里numOfMaxTask=2,即A和B),则共有max个间隔,其中max-1个间隔长度为n+1个intervals,还剩下最后一个间隔长度为numOfMaxTask intervals。注意这里每个字母或空格代表一个interval,每个括号里面代表一个间隔。
即(ABC)(AB_)AB。
但要注意这仅仅是当max的长度和tasks.size()可以比拟的情况。当max的长度<<tasks.size()时,max个task可以均匀分布到tasks字符串里面。比如说tasks=“AAABCDEFGQWRT”, n=2,则AAA完全可以跟其他task均匀打散。
所以最后返回max(taskSize, (data[25] - 1) * (n + 1) + numOfMaxTasks)。
代码如下:

class Solution {
public:
    /**
     * @param tasks: the given char array representing tasks CPU need to do
     * @param n: the non-negative cooling interval
     * @return: the least number of intervals the CPU will take to finish all the given tasks
     */
    int leastInterval(string &tasks, int n) {
        int taskSize = tasks.size();
        
        vector<int> data(26, 0);
        for (int i = 0; i < taskSize; ++i) {
            data[tasks[i] - 'A']++;
        }
        
        sort(data.begin(), data.end());
        
        int numOfMaxTasks = 1;
        for (int i = 24; i >= 0; --i) {
            if (data[i] == data[25]) numOfMaxTasks++;
            else break;
        }
        
        return max(taskSize, (data[25] - 1) * (n + 1) + numOfMaxTasks);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值