leetcode 621. Task Scheduler

本文介绍了一种基于优先队列的任务调度算法,该算法用于解决CPU在处理任务时考虑到冷却间隔n的任务分配问题。通过使用优先队列按任务出现频率排序,算法能够在满足冷却间隔限制的情况下,尽可能减少完成所有任务所需的总时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值