Wednesday, August 5, 2015

LeetCode [251] Flatten 2D Vector

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 herefor 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.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Vector2D
{
    vector<vector<int>>::iterator row_it, row_end;
    vector<int>::iterator col_it;

  public:
    Vector2D(vector<vector<int>> &v)
    {
        row_it = v.begin(), row_end = v.end();
        while (row_it != row_end && row_it->empty())
            row_it++;
        if (row_it != row_end)
            col_it = row_it->begin();
    }

    int next()
    {
        int v = *col_it;
        col_it++;
        if (col_it == row_it->end())
        {
            row_it++;
            while (row_it != row_end && row_it->empty())
                row_it++;
            if (row_it != row_end)
                col_it = row_it->begin();
        }
        return v;
    }

    bool hasNext()
    {
        return row_it != row_end;
    }
};

/**
 * 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();
 */

No comments:

Post a Comment