Use queue in C++ (9s)


  • 0
    S
        int magicalString(int n) {
            queue<int> magic;
            if (n<=0) return 0;
            if (n<=3) return 1;
            if (n<=4) return 2;
            int num=3,count=5;
            magic.push(1);
            magic.push(1);
            
            while (count<n){
                if (magic.front()==1){
                    count++;
                    if (magic.back()==1) magic.push(2);
                    else {
                        num++;
                        magic.push(1);
                    }
                }
                else{
                    count += 2;
                    if (magic.back()==1) { magic.push(2);magic.push(2);}
                    else{
                        magic.push(1);
                        magic.push(1);
                        if (count>n) return num+1;
                        num += 2;
                    }
                }
                magic.pop();
            }
            return num;
            
        }
    

Log in to reply
 

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