C++ solution using sets


  • 0
    T
    class Solution {
    public:
        // set is used to store the updated time at which a task can be scheduled. The first set value returns the best task to be scheduled at that particular time interval
        int leastInterval(vector<char>& tasks, int n) {
            int hash[26]={0},counter=0;
            set<pair<int,int>> s;
            for(int i=0;i<tasks.size();i++) {
                s.insert(make_pair(0,(tasks[i]-65)%26));
                hash[(tasks[i]-65)%26]++;
                }
            for(auto i = s.begin();i!=s.end();){
                   if((*i).first <= counter){
                    if(hash[(*i).second]!=0){
                        hash[(*i).second]--;
                    }
                    if(hash[(*i).second] ==0){  // all counts of a particular task has been scheduled, so it can be removed from set!
                        s.erase(i);
                        i = s.begin();
                    }
                    else{ // updating set with newer <interval,task>
                        pair<int,int> p;
                        p.first = (*i).first+n+1;
                        p.second = (*i).second;
                        s.erase(i);
                        s.insert(p);
                        i = s.begin();
                    }
                }
           counter++;
            }
            return counter;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.