class Solution { class Task { public char task; public int numTasks; } public int leastInterval(char[] tasks, int n) { if (tasks.length == 0) { return 0; } Map<Character, Task> map = new HashMap<>(); for (char c : tasks) { if (!map.containsKey(c)) { Task t = new Task(); t.task = c; t.numTasks = 0; map.put(c, t); } map.get(c).numTasks++; } Queue<Task> queue = new PriorityQueue<>((t1, t2) -> t2.numTasks - t1.numTasks); queue.addAll(map.values()); int result = 0; while (!queue.isEmpty()) { int k = n + 1; List<Task> taskList = new ArrayList<>(); while (k > 0 && !queue.isEmpty()) { Task current = queue.poll(); current.numTasks--; taskList.add(current); result++; k--; } for (Task task : taskList) { if (task.numTasks > 0) { queue.offer(task); } } if (queue.isEmpty()) break; result += k; } return result; } }
时间: 2024-11-08 21:58:01