HHR的小站
享受代码带来的快乐吧
首页
LeetCode 621. 任务调度器
2020-02-10 |HHR | 代码使人快乐, LeetCode

给定一个用字符数组表示的 CPU 需要执行的任务列表。其中包含使用大写的 A - Z 字母表示的26 种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。CPU 在任何一个单位时间内都可以执行一个任务,或者在待命状态。

然而,两个相同种类的任务之间必须有长度为 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
你需要计算完成所有任务所需要的最短时间

示例 1:

输入: tasks = ["A","A","A","B","B","B"], n = 2
输出: 8 
执行顺序: A -> B -> (待命) -> A -> B -> (待命) -> A -> B. 

注:

  1. 任务的总个数为 [1, 10000]。
  2. n 的取值范围为 [0, 100]。

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;
struct numCD {
    int num;
    int cd = 0;
};

bool cmp(numCD &n1, numCD &n2) {
    return n1.num > n2.num;
}

class letter {
private:
    numCD num[26];
    int n, time;
public:
    letter(vector<char> &tasks, int n) {
        this->n = n + 1;
        time = tasks.size();
        for (auto &i : num) {
            i.num = 0;
        }
        for (char c:tasks) {
            num[c - 'A'].num++;
        }
        sort(num, num + 26, cmp);
    }

    bool get() {
        if (time == 0) return false;
        sort(num, num + 26, cmp);
        for (int x = 0; x <= 25; x++) {
            if (num[x].num == 0) {
                break;
            }
            if (!num[x].cd) {
                num[x].num--;
                num[x].cd = n;
                time--;
                break;
            }
        }
        for (int x = 0; x < 25; x++) {
            if (num[x].cd) {
                num[x].cd--;
            }
        }
        return true;
    }
};

class Solution {
public:
    int leastInterval(vector<char> &tasks, int n) {
        letter l(tasks, n);
        int ans = 0;
        while (l.get()) {
            ans++;
        }
        return ans;
    }
};

垃圾代码,别看了

https://leetcode-cn.com/problems/task-scheduler/

respond-post-175

添加新评论

请填写称呼
请填写合法的电子邮箱地址
请填写合法的网站地址
请填写内容