C++ 16ms 13 lines using iterators


  • 0
    class Vector2D {
    private:
        pair<vector<vector<int>>::iterator, vector<vector<int>>::iterator> parent;          // parent iterators for vec2d
        pair<vector<int>::iterator, vector<int>::iterator> cur;                             // current iterators for vec2d[i]
        
        void update() {
            for (; cur.first == cur.second && parent.first != parent.second; parent.first++) {
                cur.first = parent.first->begin(), cur.second = parent.first->end();        // make sure cur is valid
            }
        }
        
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            parent.first = vec2d.begin(), parent.second = vec2d.end();                      // initialize parent
            update();                                                                       // update cur
        }
    
        int next() {
            int val = *(cur.first++);                                                       // get current value
            update();
            return val;
        }
    
        bool hasNext() {
            return cur.first != cur.second;                                                 // as long as cur is valid
        }
    };
    

Log in to reply
 

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