方法一:Priority Queue
由于相同的间隔至少为n,所以可以把 n+1 看作一组。利用greedy的思想,每次按照剩余的frequency来填充当前 n+1 个time slot。注意需要一个临时的数组记录新的frequency,等 n+1 个time slot分配完以后再放入优先队列中。
这种方法的本质就是利用greedy做simulation。
class Solution { public: int leastInterval(vector<char>& tasks, int n) { priority_queue<int> q; // frequency of remaining tasks unordered_map<char,int> count; for (char task:tasks) ++count[task]; for (auto x:count) q.push(x.second); int res=0; while (!q.empty()){ // assign to n+1 slots according to frequency int slots=n+1; vector<int> new_freq; while (slots){ if (q.empty()){ if (new_freq.size()==0) return res; else{ res += slots; // we need insert idles break; } }else{ int cur=q.top(); q.pop(); if (cur-1>0) new_freq.push_back(cur-1); --slots; ++res; } } for (auto x:new_freq) q.push(x); } return res; } };
原文:https://www.cnblogs.com/hankunyan/p/11301962.html