forked from fengvyi/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
281. Zigzag Iterator.cpp
73 lines (66 loc) · 1.74 KB
/
281. Zigzag Iterator.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
it1 = v1.begin();
it2 = v2.begin();
end1 = v1.end();
end2 = v2.end();
}
int next() {
if(it1 == end1) return *it2++;
if(it2 == end2) return *it1++;
int res = turn ? *it1++ : *it2++;
turn = !turn;
return res;
}
bool hasNext() {
return it1 != end1 || it2 != end2;
}
private:
vector<int>::iterator it1, it2, end1, end2;
bool turn = true;
};
// Follow up: What if you are given k 1d vectors? How well can your code be extended to such cases?
// Solution: For k vectors, use two queues to store iterators and `end` iterators.
class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
auto it1 = v1.begin();
auto it2 = v2.begin();
auto end1 = v1.end();
auto end2 = v2.end();
it.push_back(it1);
it.push_back(it2);
end.push_back(end1);
end.push_back(end2);
/* If given k vectors
(vector<vector<int>>& v){
for(auto x: v){
auto i = v.begin();
auto j = v.end();
it.push_back(i);
end.push_back(j);
}
}
*/
}
int next() {
auto x = it.front();
it.pop_front();
int res = *x++;
it.push_back(x);
end.push_back(end.front());
end.pop_front();
return res;
}
bool hasNext() {
while(!it.empty() && it.front() == end.front()){
it.pop_front();
end.pop_front();
}
return !it.empty();
}
private:
deque<vector<int>::iterator>it;
deque<vector<int>::iterator>end;
};