Sharing C++ Solution using iterator only


  • 0
    Y
    class Vector2D {
    public:
        Vector2D(vector<vector<int>>& vec2d) {
            main_it = vec2d.begin();
            end_bnd = vec2d.end();
            while(main_it != end_bnd && (*main_it).begin() == (*main_it).end()){
                ++ main_it;
            }
            if(main_it != end_bnd)
                sub_it = (*main_it).begin();
        }
    
        int next() {
            int res = *sub_it;
            ++ sub_it;
            if(sub_it == (*main_it).end()){
                ++ main_it;
                while(main_it != end_bnd && (*main_it).begin() == (*main_it).end())
                    ++ main_it;
                if(main_it != end_bnd){
                    sub_it = (*main_it).begin();
                }else{
                    sub_it = (*main_it).end();
                }
            }
            return res;
        }
    
        bool hasNext() {
            if(main_it == end_bnd || (main_it == end_bnd - 1 && sub_it == (*main_it).end()))
                return false;
            return true;
        }
    private:
        vector<vector<int>>::iterator main_it;
        vector<vector<int>>::iterator end_bnd;
        vector<int>::iterator sub_it;
    };

Log in to reply
 

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