class Solution {
public int leastInterval(char[] tasks, int n) {
// 贪心算法
// 26个字母
int[] buckets = new int[26];
// 统计每种任务的出现个数
// task中都是大写字母
for(int i=0;i<tasks.length;i++){
buckets[tasks[i]-'A']++;
}
// 排序 从小到大
Arrays.sort(buckets);
// 统计出现次数最多的任务的数量
int maxTimes = buckets[25];
// 统计同样多的任务
int maxCount = 1;
for(int i=25;i>=1;i--){
// 从后往前找同样多的任务数
if(buckets[i]==buckets[i-1]){
// 相等则maxCount加一
maxCount++;
}else{
// 不等则结束循环
break;
}
}
// 任务少的情况下
int res = (maxTimes-1)*(n+1)+maxCount;
// 任务多的情况,冷却时间有时可以不用管,直接取所有任务数的长度即可
return Math.max(res,tasks.length);
}
}
每日一道Leetcode - 621. 任务调度器 【贪心算法】
猜你喜欢
转载自blog.csdn.net/weixin_41041275/article/details/112131894
今日推荐
周排行