-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path601.flatten-2d-vector.cpp
58 lines (52 loc) · 1.21 KB
/
601.flatten-2d-vector.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Tag: Iterator
// Time: O(*1)
// Space: O(N)
// Ref: Leetcode-251
// Note: -
// Design an iterator to realize the function of flattening two-dimensional vector.
//
// Example 1:
// ```
// Input:[[1,2],[3],[4,5,6]]
// Output:[1,2,3,4,5,6]
// ```
// Example 2:
// ```
// Input:[[7,9],[5]]
// Output:[7,9,5]
// ```
//
//
class Vector2D {
public:
stack<vector<int>> st;
stack<int> res;
Vector2D(vector<vector<int>>& vec2d) {
// Initialize your data structure here
for (int i = vec2d.size() - 1; i >=0; i--) {
st.push(vec2d[i]);
}
}
int next() {
// Write your code here
int top = res.top();
res.pop();
return top;
}
bool hasNext() {
// Write your code here
while (!st.empty() && res.empty()) {
vector<int> cur = st.top();
st.pop();
for (int i = cur.size() - 1; i >= 0; i--) {
res.push(cur[i]);
}
}
return !res.empty();
}
};
/**
* Your Vector2D object will be instantiated and called as such:
* Vector2D i(vec2d);
* while (i.hasNext()) cout << i.next();
*/