Task Scheduler

本文深入探讨了LeetCode网站上的TaskScheduler问题,通过实例讲解了如何利用贪心算法解决任务调度问题,特别是如何通过频率最大字符的分隔和填充策略来最小化完成所有任务所需的间隔数。

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

[leetcode]Task Scheduler

链接:https://leetcode.com/problems/task-scheduler/description/

Question

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

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

Solution

class Solution {
public:
  // 这道题真的是靠智商。。
  // 步骤如下:以 AACCCDDEEE 3 为例子
  // 1、对于一个字符串,找到频率最大的一部分字符,如CE
  // 2、以CE为分隔符,3为分隔间距划分如CEXXCEXXCE[长度是(3-1)*(4)+2]
  // 3、将剩下的字符填入中间的空位(尽量填的均匀--也就是空的区间大小差不多,不会出现3和1,而是2和2)
  // 4、对于3,如果剩下的字符个数 <= 中间的空位,可以直接填满,此时长度是(3-1)*(4)+2。
  //   如果剩余的字符 > 中间的空位,填不满,但是实际上可以填在每个分割区间的最后面,长度是字符串长度。
  // 5、由于此题只需要求长度,因此直接找4中的较大值就可以了
  int leastInterval(vector<char>& tasks, int n) {
    vector<int> vec;
    vec.resize(26, 0);
    for (int i = 0; i < tasks.size(); i++) vec[tasks[i]-'A']++;
    sort(vec.begin(), vec.end());
    int cnt = 0;
    int max_val = vec[vec.size()-1];
    for (int i = vec.size()-1; i >= 0; i--)
      if (vec[i] == max_val)
        cnt++;

    return max((int)tasks.size(), (max_val-1)*(n+1)+cnt);
  }
};

思路:贪心算法,具体看注释。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值