###### 轻春

Github: https://github.com/gutouyu

## 一、问题描述

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) {
map<char, int> m;
for (int i = 0; i < tasks.size(); ++i) {
}
priority_queue<int> pq;
for (auto ite : m){
pq.push(ite.second);
}
int cycle = n + 1, ret = 0;
while(!pq.empty()){
vector<int> tmp;
int time = 0;
for (int i = 0; i < cycle; ++i) {
if (!pq.empty()){
tmp.push_back(pq.top());
pq.pop();
time++;
}
}

for (auto cnt : tmp){
int remainCnt = cnt - 1;
if(remainCnt > 0)pq.push(remainCnt);
}
if(pq.empty()) ret += time;//如果是最后一次调度，不在需要idle来填充
else ret += cycle;
}
return ret;
}
};

#### 快乐玩转Ant之二

2017年05月06日 14:25

#### leetcode -- 621. Task Scheduler【贪婪算法 + 数学公式化 + 逻辑证明方式】

2017-06-21 23:30:48

2017-06-21 23:08:20

2017-06-29 21:40:32

2017-09-07 13:12:09

#### leetcode 621. Task Scheduler (贪心)

2017-08-17 09:38:14

2018-02-04 09:22:54

2017-06-20 13:37:27

2017-10-12 15:25:48

2017-07-15 20:11:12