首页 > 其他 > 详细

LeetCode 621. Task Scheduler

时间:2019-08-05 11:53:08      阅读:67      评论:0      收藏:0      [点我收藏+]

方法一: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;
    }
};

 

LeetCode 621. Task Scheduler

原文:https://www.cnblogs.com/hankunyan/p/11301962.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!