C++ implementation with detailed explanation referred to the top voted solution


  • 0
    2

    Thanks the excellent design by the @Step .....

    Here is the C++ CODE with detailed explanation .

     class Vector2D {
        public:
            Vector2D(vector<vector<int>>& vec2d) {
                begin = vec2d.begin();
                /** point to the next element of the last element, so is nothing **/
                end = vec2d.end();
            }
        
            int next() {
                hasNext();
                return (*begin)[cur++];
            }
        
            bool hasNext() {
                /** move forward the begin iterator if the cur reach the end of the current begin()'s end **/
                while(begin != end && cur == (*begin).size()) {
                    begin++;
                    cur = 0;
                }
                /** check the begin is valid **/
                return begin != end;
            }
            
        private:
            /** record the index of the begin iterator **/
            int cur = 0;
            /** record the begin and end iterator of the outer array **/
            vector<vector<int>>::iterator begin, end;
        };
        
        /**
         * Your Vector2D object will be instantiated and called as such:
         * Vector2D i(vec2d);
         * while (i.hasNext()) cout << i.next();
         */

Log in to reply
 

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