Skip to content

Commit 81a8410

Browse files
authored
Create rle-iterator.cpp
1 parent 108e1c7 commit 81a8410

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

C++/rle-iterator.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class RLEIterator {
5+
public:
6+
RLEIterator(vector<int> A)
7+
: A_(move(A)),
8+
i_{0},
9+
cnt_{0} {
10+
11+
}
12+
13+
int next(int n) {
14+
while (i_ < A_.size()) {
15+
if (n > A_[i_] - cnt_) {
16+
n -= A_[i_] - cnt_;
17+
cnt_ = 0;
18+
i_ += 2;
19+
} else {
20+
cnt_ += n;
21+
return A_[i_ + 1];
22+
}
23+
}
24+
return -1;
25+
}
26+
27+
private:
28+
const vector<int> A_;
29+
int i_;
30+
int cnt_;
31+
};
32+
33+
/**
34+
* Your RLEIterator object will be instantiated and called as such:
35+
* RLEIterator obj = new RLEIterator(A);
36+
* int param_1 = obj.next(n);
37+
*/

0 commit comments

Comments
 (0)