leetcode621——優先佇列的思路

dtwd886發表於2020-10-04

題目連結:https://leetcode-cn.com/problems/task-scheduler/

思路:數量多的先安排任務,少的後安排,每次僅僅採用每類任務個數減1的方式

class Solution {
public:
    struct node
    {
        node():ch('.'),count(0){}
        node(char c,int n):ch(c),count(n)
        {

        }
        bool friend operator<(node x,node y)
        {
            if(x.count!=y.count)
                return x.count<y.count;
            else return x.ch<y.ch;
        }
        char ch;
        int count;
    };

    int leastInterval(vector<char>& tasks, int n) {
        unordered_map<char,int>mapp;
        priority_queue<node>pri_que;
        int result=0;
        for(auto ch:tasks)
        {
            if(mapp.count(ch))
            {
                mapp[ch]++;
            }
            else
            {
                mapp[ch]=1;
            }
        }
        for(auto pair_temp:mapp)
        {
            pri_que.push(node(pair_temp.first,pair_temp.second));
        }
        while(!pri_que.empty())
        {
            vector<node>vec_temp;
            for(int i=0;i<n+1;i++)
            {

                if(!pri_que.empty())
                {
                    node lef_node=pri_que.top();
                    pri_que.pop();
                    lef_node.count-=1;
                    cout<<lef_node.ch<<" "<<lef_node.count<<endl;
                    if(lef_node.count!=0)
                    {
                        vec_temp.push_back(lef_node);
                    }
                }
                result++;
                if(pri_que.empty()&&vec_temp.empty())break;
            }
            for(auto temp_node:vec_temp)
            {
                pri_que.push(temp_node);
            }
        }
        return result;
    }
};

 

相關文章