621. Task Scheduler
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.
Example 1:
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]
public class Solution { public int leastInterval(char[] tasks, int n) { if (tasks.length == 0) return 0; HashMaptaskMap = new HashMap<>(); for (char t : tasks) { taskMap.put(t, taskMap.getOrDefault(t, 0) + 1); } PriorityQueue > toDo = new PriorityQueue<>( (a, b) -> a.getValue() == b.getValue() ? a.getKey() - b.getKey() : b.getValue() - a.getValue()); toDo.addAll(taskMap.entrySet()); int steps = 0; while (!toDo.isEmpty()) { List > processed = new ArrayList<>(); int currentRoundSteps = n; while (currentRoundSteps >= 0 && !toDo.isEmpty()) { Map.Entry item = toDo.poll(); --currentRoundSteps; ++steps; if (item.getValue() > 1) { item.setValue(item.getValue() - 1); processed.add(item); } } if (!processed.isEmpty()) { steps += currentRoundSteps + 1; } toDo.addAll(processed); } return steps; }}
358. Rearrange String k Distance Apart
Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string ""
.
Example 1:
str = "aabbcc", k = 3Result: "abcabc"The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 Answer: ""It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2Answer: "abacabcd"Another possible answer is: "abcabcda"The same letters are at least distance 2 from each other.