leetcode练习 Task Scheduler

来源:互联网 发布:室内网络布线 编辑:程序博客网 时间:2024/05/23 10:45

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.

Example1:

Input: tasks = ["A","A","A","B","B","B"], n = 2Output: 8Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].

这是一个很巧妙的题。做这道题的是谁是和同学一起在思考,最初的想法是,寻找可以去做的任务中,剩余最多的那项,代码比较繁琐,后来思考之后找到一种简单的方法:

通常情况下,可以使用最多的那项任务安排的最密集的方式完成,将其他任务填充在之间的空闲,即是这种情况的最优解,其他情况下,剩余的任务有多的,空闲不够填充,就会填在后面。这个时候没有空闲,长度就是任务的长度。代码如下

class Solution {public:    int leastInterval(vector<char>& tasks, int n) {        map<char,int>mp;        int count = 0;        for(auto e : tasks)        {            mp[e]++;            count = max(count, mp[e]);        }        int ans = (count-1)*(n+1);        for(auto e : mp) if(e.second == count) ans++;        return max((int)tasks.size(), ans);    }};

简洁明了,巧妙,很不错的题目。