版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/smmyy022/article/details/82871273
题解
比较有意思的题,不太好归类,应该是贪心。
这题的只要换个思路就好做了,就是算idle的时间有多长,因为task必然耗时。
给一篇写得很完备的英文解析
简介几个核心点:
- 有最大频率的任务,会创造最长的时间间隔如 A _ _ A _ _ A (n=2)
- 这些间隔 _ 可用来放置其他任务,或者留作idle
- 如果间隔不够,那么恭喜你我们不需要idle(思考为什么)
- 特例 有相同最大频率的不同任务。
Code
class Solution {
public:
int cot[26];
int leastInterval(vector<char>& tasks, int n) {
memset(cot,0,sizeof(cot));
for(char c:tasks){
cot[c-'A']++;
}
int sum=0,cur_max = 0, max_count=0;
for(int i=0;i<26;i++){
sum+=cot[i];
if(cot[i]==cur_max) max_count++;
if(cur_max < cot[i]){
cur_max = cot[i];
max_count = 1;
}
}
int countparts = cur_max-1;
int partLen = n - max_count+1;
int slots = countparts*partLen;
int idles = max(0 , slots - (sum- max_count*cur_max) );
return sum+idles;
}
};