Leetcode 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].

题目分析:
这道题可以用贪心策略来解决,一个直观的贪婪想法就是,尽可能让出现次数多的任务先做,这样在它的冷却期内就可以做其他的任务,使效率最大化。为了实现这点,需要一个数组来记录每个字母下的任务数量,已找出每一轮还剩下任务数最多的一个字母放入schedule。同时,需要另一个数组记录每种任务的冷却期,只有冷却期为0的任务才纳入可能放入schedule的考量范围内。每一轮这样做,直到已完成的任务数量达到任务总数为止,返回总共的轮数times。

具体步骤:

  • step1:根据输入的tasks,统计每种任务的数量,记录在数组中。
  • step2:每一轮找到不在冷却状态的任务中数量最多的,放入task schedule,如果不存在则此轮空闲。
  • step3:对于放入schedule的任务,任务数减一,完成度加一,并将冷却时间设置为n ,同时每一轮所有的冷却倒计时都要减一。
  • step4:循环直到完成度达到总任务数,返回总时间。

代码:

#include <iostream>
using namespace std;
#include <vector>

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {

        vector<int> t(26, 0);       //记录每种任务的数量 
        for (int i = 0; i < tasks.size(); i++){
            t[tasks[i] - 'A']++;        
        }
        vector<int> cool(26, 0);    //记录每种任务的冷却倒计时 
        int time = 0, complete = 0;     //记录总时间、完成度 
        while (complete < tasks.size()){
            time++;
            int num = 0, x = -1;        //num表示当前最大任务数,x表示指向最大任务数的下标 
            for (int i = 0; i < 26; i++){
                if (cool[i] == 0 && t[i] > num){
                    x = i;
                    num = t[i];
                }
                if (cool[i] != 0) cool[i]--;    //每一轮所有的冷却倒计时都要减一 
            }
            if (x != -1){   //找到能放入schedule的任务,则任务数减一,完成度加一,并将冷却时间设置为n 
                t[x]--;
                cool[x] = n;
                complete++;
            }
        }
        return time;    //返回总时间 
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值