My c++ solution, no iterator needed


  • 0
    A

    The idea is that use "hasNext" to put next available number at position [0][0], and function "next" is to read the number at location [0][0], then call "hasNext" to put next number at that position.
    Of course, if there's no number inside, "hasNext" will output false.

    class Vector2D {
        vector<vector<int>> vec2d;
    public:
        Vector2D(vector<vector<int>>& vec2d): vec2d(vec2d){
            
        }
    
        int next() {
            hasNext();
            int res = vec2d[0][0];
            vec2d[0].erase(vec2d[0].begin());
            hasNext();
            return res;
        }
    
        bool hasNext() {
            while(vec2d.size()&&vec2d[0].empty()) vec2d.erase(vec2d.begin());
            return vec2d.size();
        }
    };
    

Log in to reply
 

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