621. Task Scheduler

本文介绍了一个关于CPU任务调度的问题,特别关注了在特定冷却间隔限制下如何安排任务以达到最短完成时间的目标。文中详细解释了算法实现,并提供了一个C++示例代码。

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

621. Task Scheduler

Problem

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:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].

Implmentation

1\ Consider the slot we need with n intevals. Find the most frequent number which is the largest slots num - 1. So the time is (num1)n+frelargest
2\ The above result should compare with the size of tasks. As the kinds of tasks may be larger than n, if larger, return the size of tasks.

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        int num_tasks = tasks.size();
        int res = 0;

        if(!num_tasks)
            return res;
        if(!n)
            return num_tasks;

        map<char, int> rec;
        int biggest = 0;

        for(int idx = 0; idx < num_tasks; idx++) {
            rec[tasks[idx]]++;
            if(biggest < rec[tasks[idx]]) {
                biggest = rec[tasks[idx]];
            }    
        }

        int num_biggest = 0;
        for(map<char, int>::iterator it = rec.begin(); it != rec.end(); it++) {
            if(it->second == biggest) {
                num_biggest++;
            }    
        }

        res = (n+1)*(biggest - 1) + num_biggest;

        return res > num_tasks? res:num_tasks;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值