Concise C++ Iterative Solution, 16 ms


  • 0
    C

    Use pointers to avoid copying vectors.

    class NestedIterator {
        list<vector<NestedInteger>*> stack;
        vector<NestedInteger>* topList;
        unordered_map<vector<NestedInteger>*, int> indices;
        
    public:
        NestedIterator(vector<NestedInteger> &nestedList) 
        {
            stack.push_back(&nestedList);
            indices[&nestedList] = -1;
        }
    
        int next() {
            return topList->at(indices[topList]).getInteger();
        }
    
        bool hasNext() {
            
            while(not stack.empty())
            {
                topList = stack.back();
                indices[topList]++;
                int topIndex = indices.at(topList);
                if(topIndex >= topList->size())
                    stack.pop_back();
                else
                {
                    if(topList->at(topIndex).isInteger())
                        return true;
                    vector<NestedInteger>& thisList = topList->at(topIndex).getList();
                    stack.push_back(&thisList);
                    indices[&thisList] = -1;
                }    
            }
            
            return false;
        }
    };
    

Log in to reply
 

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