zoukankan      html  css  js  c++  java
  • 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:

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

    Approach #1: C++. 

    class Solution {
    public:
        int leastInterval(vector<char>& tasks, int n) {
            int size = tasks.size();
            if (size == 0) return 0;
            vector<int> temp(30, 0);
            for (int i = 0; i < size; ++i) {
                int idx = tasks[i] - 'A';
                temp[idx]++;
            }
            sort(temp.begin(), temp.end(), [](int& a, int& b) { return a > b; });
            int f = temp[0];
            int t = 1;
            for (int i = 1; i < 30; ++i) 
                if (temp[i] == f) t++;
                else break;
            int ans = (f - 1) * (n + 1) + t;
            if (ans < size) return size;
            else return ans;
        }
    };
    

      

    Approach #2: C++. [STL]

    // Author: Huahua
    // Runtime: 56 ms
    class Solution {
    public:
        int leastInterval(vector<char>& tasks, int n) {
            vector<int> count(26, 0);        
            for (const char task : tasks) 
                ++count[task - 'A'];
            const int max_count = *max_element(count.begin(), count.end());
            size_t ans = (max_count - 1) * (n + 1);
            ans += count_if(count.begin(), count.end(),
                            [max_count](int c){ return c == max_count; });
            return max(tasks.size(), ans);
        }
    };
    

      

    Analysis:

    @Huahua

    count_if

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    [CSP-S模拟测试]:attack(支配树+LCA+bitset)
    [杂题]:C/c(二分答案)
    [杂题]:B/b(二分答案)
    二维莫队(离线)
    [CSP-S模拟测试]:联盟(搜索+树的直径)
    [CSP-S模拟测试]:蔬菜(二维莫队)
    [CSP-S模拟测试]:施工(DP+单调栈+前缀和)
    [CSP-S模拟测试]:画作(BFS+数学)
    [CSP-S模拟测试]:折射(DP)
    [CSP-S模拟测试]:养花(分块)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10212627.html
Copyright © 2011-2022 走看看