1: class Vector2D {
2: private:
3: int i, j;
4: vector<vector<int>> vecs;
5: public:
6: Vector2D(vector<vector<int>>& vec2d) {
7: vecs = vec2d;
8: i = 0, j = 0;
9: }
10: int next() {
11: return vecs[i][j++];
12: }
13: bool hasNext() {
14: while (i < vecs.size() && vecs[i].size() == j) {
15: i++, j = 0;
16: }
17: return i < vecs.size();
18: }
19: };
20: /**
21: * Your Vector2D object will be instantiated and called as such:
22: * Vector2D i(vec2d);
23: * while (i.hasNext()) cout << i.next();
24: */
Saturday, July 16, 2016
251. Flatten 2D Vector
I was thinking to maintain a queue. But soon, I realized I only need to maintain the row index and column index. In hasNext() we need to check if row index reaches the boundary and the column index reaches the boundary. If row index is not reaching the boundary and column index is on the boundary, we need to move one row below and initialize column index to 0. The reason we use while loop is there could be empty rows. We should return true if row index is not on the boundary.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment