Tuesday, December 29, 2015

L 251. Flatten 2D Vector ----------M

Design and implement an iterator to flatten a 2d vector. It should support the following operations: next and hasNext.

 

Example:

Vector2D iterator = new Vector2D([[1,2],[3],[4]]);

iterator.next(); // return 1
iterator.next(); // return 2
iterator.next(); // return 3
iterator.hasNext(); // return true
iterator.hasNext(); // return true
iterator.next(); // return 4
iterator.hasNext(); // return false

 

Notes:

  1. Please remember to RESET your class variables declared in Vector2D, as static/class variables are persisted across multiple test cases. Please see here for more details.
  2. You may assume that next() call will always be valid, that is, there will be at least a next element in the 2d vector when next() is called.

 

Follow up:

As an added challenge, try to code it using only iterators in C++ or iterators in Java.


    A:
    关键点是:可能包含是empty list    

    class Vector2D {
    public:
        Vector2D(vector<vector<int>>& v) {
            val = v;
            m = v.size();
            n = 0;
            if(m != 0)
                n = v[0].size();
            i = 0;
            j = 0;
        }
        
        int next() {
            int res =  val[i][j];
            ++j; // simply update, since hasNext would be called
            return res;
        }
        
        bool hasNext() {        
            while(i<m && j==n){
                i++;
                if(i==m){
                    return false;
                }
                j = 0;
                n = val[i].size();;
            }
            return true;
        }
    private:
        vector<vector<int>> val;
        int i,j;
        int m,n;
    };
    
    /**
     * Your Vector2D object will be instantiated and called as such:
     * Vector2D* obj = new Vector2D(v);
     * int param_1 = obj->next();
     * bool param_2 = obj->hasNext();
     */


    Mistakes:
    1:     允许  有空的list存在。
    above code works on windows, and ubuntu, but failed on Leetcode. Seems not my fault


    No comments:

    Post a Comment