-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay22.cpp
More file actions
94 lines (78 loc) · 1.99 KB
/
Day22.cpp
File metadata and controls
94 lines (78 loc) · 1.99 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
This problem was asked by Uber.
Implement a 2D iterator class. It will be initialized with an array of arrays, and should implement the following methods:
- next(): returns the next element in the array of arrays. If there are no more elements, raise an exception.
- has_next(): returns whether or not the iterator still has elements left.
For example, given the input [[1, 2], [3], [], [4, 5, 6]], calling next() repeatedly should output 1, 2, 3, 4, 5, 6.
Do not use flatten or otherwise clone the arrays. Some of the arrays can be empty.
*/
#include <bits/stdc++.h>
using namespace std;
class Iterator
{
int currIdx;
vector<vector<int>> arr;
vector<vector<int>::iterator> start;
vector<vector<int>::iterator> end;
public:
Iterator(vector<vector<int>> &arr)
{
this->arr = arr;
int n = arr.size();
start.resize(n);
end.resize(n);
currIdx = 0;
for (int i = 0; i < n; i++)
{
start[i] = arr[i].begin();
end[i] = arr[i].end();
}
}
bool has_next()
{
for (int i = currIdx; i < arr.size(); i++)
{
if (start[i] != end[i])
{
return true;
}
}
return false;
}
int next()
{
try
{
if (!has_next())
{
throw runtime_error("No more Element");
}
if (start[currIdx] == end[currIdx])
{
currIdx++;
return next();
}
else
{
return *start[currIdx]++;
}
}
catch (runtime_error &e)
{
cerr << "Exception Caught: " << e.what() << endl;
}
return INT_MIN;
}
};
int main()
{
vector<vector<int>> arr = {{1, 2}, {3}, {}, {4, 5, 6}};
Iterator it(arr);
while (it.has_next())
{
cout << it.next() << " ";
}
// Check Exception
it.next();
return 0;
}