Storing the integers in a vector


  • 0
    R

    In this solution, we will iterate through the vector of nested list and store the individual integers in the vector. This solution will take up less memory(which is size of number of all the integer elements) as opposed to the solution where we store each NestedInteger element in a stack. Each NestedInteger element can take up a lot of memory. In our case it will store all the integer elements and the functions will also take up space. Also hasNext() is O(1) and next() is O(1)

    class NestedIterator {
    public:
        vector<int> unflattenedList;
        int pointer =0;
        
        void unflatten(vector<NestedInteger> &nestedList)
        {
            for (int i = 0; i < nestedList.size(); i++)
            {
                NestedInteger a = nestedList[i];
                
                if (a.isInteger() == false)
                {
                    unflatten(a.getList());
                }
                else
                {
                    unflattenedList.push_back(a.getInteger());
                }
            }
        }
        
        NestedIterator(vector<NestedInteger> &nestedList)
        {
            unflatten(nestedList);
        }
        
    
        int next()
        {
            int res = unflattenedList[pointer];
            pointer++;
            return res;
        }
    
        bool hasNext()
        {
            if (unflattenedList.size() > pointer)
            {
                return true;
            }
            
            return false;
        }
    };
    

Log in to reply
 

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