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:
- 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.
- You may assume that
next()
call will always be valid, that is, there will be at least a next element in the 2d vector whennext()
is called.
这道题很简单,没什么复杂。唯一要注意的一点是,2D vector的每一行的大小不一定一样,所以用 v.size() * v[0].size() 去计算总体的大小是不对的。以及v传进来后,要把它放入自己的数据结构,就是把它flattern,一维化。
class Vector2D { int index; vector<int> data; public: Vector2D(vector<vector<int>>& v) { for (auto &row : v) { for (int &it : row) { data.push_back(it); } } index = 0; } int next() { return data[index++]; } bool hasNext() { return index < data.size(); } }; /** * 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