Cpp easy to understand, but 36ms


  • 0
    W
    class NestedIterator {
    public:
        NestedIterator(vector<NestedInteger> &nestedList) {
            int nsize = nestedList.size();
            for(int i = 0; i < nsize; ++i){
                if(nestedList[i].isInteger()){
                    int val = nestedList[i].getInteger();
                    flat.push_back(val);
                }
                else{
                    vector<NestedInteger> curNest = nestedList[i].getList();
                    NestedIterator *sub = new NestedIterator(curNest);
                    while(sub->hasNext()){
                        flat.push_back(sub->next());
                    }
                }
            }
            vsize = flat.size();
        }
    
        int next() {
            return flat[idx++];
        }
    
        bool hasNext() {
            return idx!=vsize;
        }
    
    private:
        int idx = 0;
        int vsize = 0;
        vector<int> flat;
    };

Log in to reply
 

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