12ms C++ Iterators Only - No Indices - Detailed Comments


  • 0
    B

    So the only new variables in memory are 3 iterators, actually was pretty fast, beating like 93%, detailed comments in the code. Just drop me a comment if anything is unclear.

    class Vector2D {
    private:
        vector<vector<int>>::iterator vit, vend; // outer vector interators
        vector<int>::iterator it; // inner vector iterator
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            vit=vec2d.begin();
            vend=vec2d.end();
            if (vit!=vend) it=vit->begin();
        }
    
        int next() {
            return *it++;
        }
    
        bool hasNext() {
            // handles case of input vector == []
            if (vit==vend) return false;
            
            // handles case of a valid return from current inner vector iterator
            if (it!=vit->end()) return true;
            
            // next we look at when current inner iterator reaches the end of current inner vector
            // --------------------------- //
            vit++;
            
            // keep looping until we get an non-empty inner vector or reach the end of outer vector
            while (vit->empty() && vit!=vend) vit++;
            
            // we have reached the end of the outer vector
            if (vit==vend) return false;
            
            // start on a new non-empty inner vector
            it=vit->begin();
            return true;
            // --------------------------- //
        }
    };
    

Log in to reply
 

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