Skip to content

Commit 70c3a07

Browse files
committed
Add better code with amortized O(1)
1 parent cbbfead commit 70c3a07

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

232/step4.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Amortized O(1)となるコードを誤解していたのを指摘されたので、書き直す。
3+
push時にpush_stackにpop_stackから要素を移動させてくる必要はない。
4+
pop_stackの中身が足りなくなってから(peek/pop時)push_stackの要素を移動させてくれば良く、その逆の移動は不要。
5+
*/
6+
class MyQueue {
7+
public:
8+
stack<int> push_stack;
9+
stack<int> pop_stack;
10+
11+
MyQueue() {}
12+
13+
void push(int x) {
14+
push_stack.push(x);
15+
}
16+
17+
int pop() {
18+
int pop_value = peek();
19+
pop_stack.pop();
20+
return pop_value;
21+
}
22+
23+
int peek() {
24+
if (empty()) {
25+
return -1;
26+
}
27+
if (pop_stack.empty()){
28+
while (!push_stack.empty()) {
29+
pop_stack.push(push_stack.top());
30+
push_stack.pop();
31+
}
32+
}
33+
return pop_stack.top();
34+
}
35+
36+
bool empty() {
37+
return push_stack.empty() && pop_stack.empty();
38+
}
39+
};
40+
41+
/**
42+
* Your MyQueue object will be instantiated and called as such:
43+
* MyQueue* obj = new MyQueue();
44+
* obj->push(x);
45+
* int param_2 = obj->pop();
46+
* int param_3 = obj->peek();
47+
* bool param_4 = obj->empty();
48+
*/

0 commit comments

Comments
 (0)