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 = 2 Output: 8 Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
We need to arrange the characters in string such that each same character is K distance apart, where distance in this problems is time b/w two similar task execution.
Idea is to add them to a priority Q and sort based on the highest frequency.
And pick the task in each round of ‘n‘ with highest frequency. As you pick the task, decrease the frequency, and put them back after the round.
1 class Solution { 2 public int leastInterval(char[] tasks, int n) { 3 Map<Character, Integer> map = new HashMap<>(); 4 for (int i = 0; i < tasks.length; i++) { 5 map.put(tasks[i], map.getOrDefault(tasks[i], 0) + 1); 6 } 7 PriorityQueue<Map.Entry<Character, Integer>> q = new PriorityQueue<>( 8 (a, b) -> a.getValue() != b.getValue() ? b.getValue() - a.getValue() : a.getKey() - b.getKey()); 9 10 q.addAll(map.entrySet()); 11 12 int count = 0; 13 while (!q.isEmpty()) { 14 int k = n + 1; 15 List<Map.Entry> tempList = new ArrayList<>(); 16 while (k > 0 && !q.isEmpty()) { 17 Map.Entry<Character, Integer> top = q.poll(); // most frequency task 18 top.setValue(top.getValue() - 1); // decrease frequency, meaning it got executed 19 tempList.add(top); // collect task to add back to queue 20 k--; 21 count++; // successfully executed task 22 } 23 24 for (Map.Entry<Character, Integer> e : tempList) { 25 if (e.getValue() > 0) { 26 q.add(e); // add valid tasks 27 } 28 } 29 30 if (q.isEmpty()) { 31 break; 32 } 33 count = count + k; // if k > 0, then it means we need to be idle 34 } 35 return count; 36 } 37 }
原文:https://www.cnblogs.com/beiyeqingteng/p/11089618.html