-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLC0284.cpp
More file actions
executable file
·37 lines (32 loc) · 836 Bytes
/
LC0284.cpp
File metadata and controls
executable file
·37 lines (32 loc) · 836 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
/*
Problem Statement: https://leetcode.com/problems/peeking-iterator/
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
|-------------------|------|-------|
| Operations | Time | Space |
|-------------------|------|-------|
| PeekingIterator() | O(1) | O(1) |
| next() | O(1) | O(1) |
| hasNext() | O(1) | O(1) |
|-------------------|------|-------|
*/
class PeekingIterator : public Iterator {
private:
int cache;
bool is_cache;
public:
PeekingIterator(const vector<int>& nums) : is_cache(false), Iterator(nums) {}
int peek() {
if (exchange(is_cache, true))
return cache;
return cache = Iterator::next();
}
int next() {
if (exchange(is_cache, false))
return cache;
return Iterator::next();
}
bool hasNext() const {
return is_cache || Iterator::hasNext();
}
};