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.

一个CPU完成任务,每次只能完成一件,且相同任务之间必须有n个间隔。求最小任务区间。

CPU完成tasks的总时间 = 忙碌时间 + 空闲时间。很明显,忙碌时间就是tasks数量,所以只需要求出空闲时间就可以了。

统计每个任务的任务数,最多的那个记为cnt,(cnt-1)*(间隔周期+1),就是最后一个任务前的空位数量。

之后对每个任务统计,如果该任务任务数为cnt,空位数减去(cnt-1),不能减去cnt,因为完成最后一个任务以后,不需要加间隔时间,且该任务的最后一次只能加在尾部,不占用前面预留的空位。

要是该任务数小于cnt,直接把空位数减去该任务数就可以了。

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        unordered_map<char, int> m;
        int cnt = 0;
        for (auto task:tasks) {
            m[task]++;
            cnt = max(cnt, m[task]);
        }
        int n_idle = (n+1) * (cnt-1);    
        for (auto iter=m.begin(); iter!=m.end(); ++iter) {
            if (iter->second == cnt)
                n_idle -=  (cnt - 1);
            else
                n_idle -= iter->second;
        }
        n_idle = max(n_idle, 0);
        return tasks.size()+n_idle;
    }
};

 

posted @ 2017-12-06 14:46  Zzz...y  阅读(188)  评论(0编辑  收藏  举报