## 一、问题描述

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;
}
};``````

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

• TheSnowBoy_2
• 2017年06月21日 23:30
• 1732

leetcode 621
• feifeiiong
• 2017年06月21日 23:08
• 1813

621. Task Scheduler一、问题描述 Given a char array representing tasks CPU need to do. It contains capita...
• u010352603
• 2017年06月19日 16:34
• 2572

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where diffe...
• Crystal_ting
• 2017年09月07日 13:12
• 232

• c602273091
• 2017年07月15日 20:11
• 343

Leetcode 621 Task Scheduler 题目原文 Given a char array representing tasks CPU need to do. It contai...
• Zarlove
• 2017年10月12日 15:25
• 568

• yangyang074
• 2017年06月29日 21:40
• 271

【题目描述】 Given a char array representing tasks CPU need to do. It contains capital letters A to Z w...
• yj12588
• 2017年08月08日 22:42
• 108

## leetcode 621. Task Scheduler (贪心)

• exp1ore
• 2017年08月17日 09:38
• 213

## 625. Minimum Factorization & 621. Task Scheduler

• zjucor
• 2017年06月18日 14:05
• 447

举报原因： 您举报文章：LeetCode 621. Task Scheduler 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)