forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzigzag-iterator.cpp
More file actions
37 lines (32 loc) · 780 Bytes
/
zigzag-iterator.cpp
File metadata and controls
37 lines (32 loc) · 780 Bytes
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
// Time: O(n)
// Space: O(k)
class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
if (!v1.empty()) {
q.emplace(v1.size(), v1.cbegin());
}
if (!v2.empty()) {
q.emplace(v2.size(), v2.cbegin());
}
}
int next() {
const auto len = q.front().first;
const auto it = q.front().second;
q.pop();
if (len > 1) {
q.emplace(len - 1, it + 1);
}
return *it;
}
bool hasNext() {
return !q.empty();
}
private:
queue<pair<int, vector<int>::const_iterator>> q;
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/