leetcode 621. Task Scheduler

leetcode 621. Task Scheduler

Question stem

Give you a list of tasks that the CPU needs to perform, represented by the character array tasks. Each letter represents a different kind of task. Tasks can be executed in any order, and each task can be executed within 1 unit of time. In any unit of time, the CPU can complete a task or be in a standby state.
However, there must be a cooling time of an integer n between two tasks of the same type. Therefore, at least n consecutive units of time the CPU is executing different tasks or is in a standby state.
You need to calculate the shortest time required to complete all tasks.

Example 1:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> (standby) -> A -> B -> (standby) -> A -> B
In this example, there must be a cooling time of n = 2 between two tasks of the same type, and it takes only one unit of time to execute a task. So the (standby) state appeared in the middle.

Example 2:
Input: tasks = ["A", "A", "A", "B", "B", "B"], n = 0
Output: 6
Explanation: In this case, any size is The arrangement of 6 can meet the requirements, because n = 0
["A","A","A","B","B","B"]
["A","B","A", "B","A","B"]
["B","B","B","A","A","A"]
…and
so on

Example 3:
Input: tasks = ["A","A","A","A","A","A","B","C","D","E","F ","G"], n = 2
Output: 16
Explanation: A possible solution is:
A -> B -> C -> A -> D -> E -> A -> F -> G -> A -> (standby) -> (standby) -> A -> (standby) -> (standby) -> A

Tip:
1 <= task.length <= 104
tasks[i] is the uppercase English letter
n, the value range is [0, 100]

answer

So clever, visualize the matrix, starting from the penultimate row to align and fill. My idea at the beginning was actually the same, but I wanted to rely on filling, so it’s not easy to do.
About the usage of accumulate:

accumulate(起始迭代器,尾迭代器,初始值,对相邻元素的操作);

It happens that the operation of adjacent elements is set to: if the number of times is equal to the maximum number, return the value ++, and then pass the capture value through [=]

class Solution {
    
    
public:
    int leastInterval(vector<char>& tasks, int n) {
    
    
        unordered_map<char,int> tasksMap;
        int maxSameTaskCount = 0;
        //遍历任务列表,统计每种任务出现的次数,同时获得出现次数最多的任务
        for(auto i : tasks){
    
    
            tasksMap[i]++;
            maxSameTaskCount = max(maxSameTaskCount,tasksMap[i]);
        }
        //获取出现次数与最多次数相同的任务个数
        int longestTaskCount = accumulate(tasksMap.begin(),tasksMap.end(),0,[=](int res,auto& i){
    
    
            return res += (i.second == maxSameTaskCount);
        });
        return max((int)tasks.size(),(maxSameTaskCount - 1) * (n + 1) + longestTaskCount);
    }
};

My idea is basically the same as this one, but it’s a bit deviated. In fact, the filling process does not need to be simulated, just starting from the result: the bucket idea

Guess you like

Origin blog.csdn.net/weixin_43662405/article/details/110688891