[LeetCode] Flatten 2D Vector

251. Flatten 2D Vector

Design an iterator to flatten a 2D vector. It should support the next and hasNext operations.

Implement the Vector2D class:

  • Vector2D(int[][] vec) initializes the object with the 2D vector vec.
  • next() returns the next element from the 2D vector and moves the pointer one step forward. You may assume that all the calls to next are valid.
  • hasNext() returns true if there are still some elements in the vector, and false otherwise.
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
class Vector2D {
vector<pair<vector<int>::iterator, vector<int>::iterator>> st;
void move() {
if((++st.back().first) == st.back().second) st.pop_back();
}
public:
Vector2D(vector<vector<int>>& vec) {
for(int i = vec.size() - 1; i >= 0; i--) {
if(!vec[i].empty())
st.push_back({vec[i].begin(), vec[i].end()});
}
}

int next() {
int res = *st.back().first;
move();
return res;
}

bool hasNext() {
return !st.empty();
}
};

/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D* obj = new Vector2D(vec);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/19/PS/LeetCode/flatten-2d-vector/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.