leetcode 621. Task Scheduler

来源:互联网 发布:网络文明有哪些 编辑:程序博客网 时间:2024/06/07 06:35

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 = 2Output: 8Explanation: 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].

1、贪心,利用优先队列排序:队列中保存 <个数,类型> 的map,并且按照个数由大到小排序。按照词频由大到小取出n+1个或者队列中全部(若没有取出全部,则总长度要加上空闲个数),再把词频-1之后不为0的放回队列中。直到队列空了为止。——其实也和前面相同,总是选择词频最大的填入每一块。

2、priority_queue 取出第一个是 .top(); 而不是 front();

3、priority_queue 自定义类型需要重载操作符。和set、map的重载不太一样。


bool operator<(pair<int, char> a, pair<int, char> b){    return a.first > b.first;}class Solution {public:    int leastInterval(vector<char>& tasks, int n)     {        if (n == 0)  return tasks.size();        map<char, int> mp;        for (auto it : tasks)            mp[it]++;        priority_queue<pair<int, char>> pq;        for (auto it : mp)            pq.push(make_pair(it.second, it.first));                int ret = 0;        queue<pair<int, char>> tmp;        while (!pq.empty())        {            int k = n + 1;            while (k--)            {                if (!pq.empty())                {                    auto it = pq.top();                    pq.pop();                      it.first--;                    if (it.first > 0)                        tmp.push(it);                }                else if (tmp.empty())   //如果pq空了 tmp也空了 说明任务都完毕了                    return ret;                ret++;            }                        //把tmp装回去            while (!tmp.empty())            {                pq.push(tmp.front());                tmp.pop();            }        }        return ret;    }};