标签:blog 不为 pos style log lan nbsp cte without
原题链接在这里:https://leetcode.com/problems/task-scheduler/description/
题目:
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:
题解:
类似Rearrange String k Distance Apart.
想要最少的interval完成所有task, 需要先去完成frequency最高的task.
求出每个task的frequency放入max heap中.
在空隙没有达到n之前 并且 max heap不为空之前 poll出frequency大的值减一后放入queue中. 计算用了多少interval.
再把queue中frequency数目还大于0的task加回max heap中.
若是还没到要求的空隙数max heap就空了, 需要加idle interval.
Time Complexity: O(task.length). 每个task都执行了一遍, 中间多出的idle interval都是通过计算一次加进count中. 最多加最大frequency次idle interval 进count.
Space: O(1). map的size最大26.
AC Java:
1 class Solution { 2 public int leastInterval(char[] tasks, int n) { 3 if(tasks == null || tasks.length == 0){ 4 return 0; 5 } 6 7 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); 8 for(char c : tasks){ 9 hm.put(c, hm.getOrDefault(c,0)+1); 10 } 11 12 PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<Map.Entry<Character, Integer>>( 13 (a, b) -> b.getValue() - a.getValue() 14 ); 15 maxHeap.addAll(hm.entrySet()); 16 17 int count = 0; 18 while(!maxHeap.isEmpty()){ 19 LinkedList<Map.Entry<Character, Integer>> que = new LinkedList<Map.Entry<Character, Integer>>(); 20 int k = n+1; 21 while(k > 0 && !maxHeap.isEmpty()){ 22 Map.Entry<Character, Integer> cur = maxHeap.poll(); 23 cur.setValue(cur.getValue()-1); 24 que.add(cur); 25 k--; 26 count++; 27 } 28 29 for(Map.Entry<Character, Integer> entry : que){ 30 if(entry.getValue() > 0){ 31 maxHeap.add(entry); 32 } 33 } 34 35 if(maxHeap.isEmpty()){ 36 break; 37 } 38 39 count += k; // k != 0 要添加idle interval 40 } 41 return count; 42 } 43 }
标签:blog 不为 pos style log lan nbsp cte without
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7750409.html