题目:
我的解法:超时了
class Solution {
public int leastInterval(char[] tasks, int n) {
int d = tasks.length;
if(d==0){
return 0;
}
// 用数组记录每个任务出现的次数
int[] count = new int[26];
for(int i=0; i<d; i++){
char c = tasks[i];
count[c-'A']++;
}
// 维护一个最大堆,按任务出现的次数从高到低排列
PriorityQueue<Character> stack = new PriorityQueue<Character>(new Comparator<Character>(){
public int compare(Character letter1, Character letter2){
return count[letter2 - 'A'] - count[letter1 - 'A'];
}
});
for(char c='A'; c<'Z'; c++){
if(count[c - 'A']>0){
stack.offer(c);
}
}
// 创建一个arraylist来维护任务,先从数量最多的任务中选
List<Character> list = new ArrayList<Character>();
int time = 0;
int finish = 0;
int wait_num = 0;
while(finish < d){
wait_num = 0;
int wait = n+1;
while(wait!=0){
if(stack.size()!=0){
char c = stack.poll();
// System.out.println(c);
list.add(c);
count[c - 'A']--;
finish++;
time++;
wait--;
}else{
wait--;
time++;
wait_num++;
}
}
for(char c: list){
if(count[c - 'A']>0){
stack.offer(c);
}
}
list.clear();
}
return time-wait_num;
}
}
官方题解:
class Solution {
public int leastInterval(char[] tasks, int n) {
Map<Character, Integer> freq = new HashMap<Character, Integer>();
for (char ch : tasks) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
// 任务总数
int m = freq.size();
List<Integer> nextValid = new ArrayList<Integer>();
List<Integer> rest = new ArrayList<Integer>();
Set<Map.Entry<Character, Integer>> entrySet = freq.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet) {
int value = entry.getValue();
nextValid.add(1);
rest.add(value);
}
int time = 0;
for (int i = 0; i < tasks.length; ++i) {
++time;
int minNextValid = Integer.MAX_VALUE;
for (int j = 0; j < m; ++j) {
if (rest.get(j) != 0) {
minNextValid = Math.min(minNextValid, nextValid.get(j));
}
}
time = Math.max(time, minNextValid);
int best = -1;
for (int j = 0; j < m; ++j) {
if (rest.get(j) != 0 && nextValid.get(j) <= time) {
if (best == -1 || rest.get(j) > rest.get(best)) {
best = j;
}
}
}
nextValid.set(best, time + n + 1);
rest.set(best, rest.get(best) - 1);
}
return time;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/task-scheduler/solution/ren-wu-diao-du-qi-by-leetcode-solution-ur9w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public int leastInterval(char[] tasks, int n) {
Map<Character, Integer> freq = new HashMap<Character, Integer>();
// 最多的执行次数
int maxExec = 0;
for (char ch : tasks) {
int exec = freq.getOrDefault(ch, 0) + 1;
freq.put(ch, exec);
maxExec = Math.max(maxExec, exec);
}
// 具有最多执行次数的任务数量
int maxCount = 0;
Set<Map.Entry<Character, Integer>> entrySet = freq.entrySet();
for (Map.Entry<Character, Integer> entry : entrySet) {
int value = entry.getValue();
if (value == maxExec) {
++maxCount;
}
}
return Math.max((maxExec - 1) * (n + 1) + maxCount, tasks.length);
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/task-scheduler/solution/ren-wu-diao-du-qi-by-leetcode-solution-ur9w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。