-
Notifications
You must be signed in to change notification settings - Fork 0
/
1381-design-a-stack-with-increment-operation.cpp
55 lines (50 loc) · 1.22 KB
/
1381-design-a-stack-with-increment-operation.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
class CustomStack {
public:
int limit;
stack<int> s;
stack<int> temp;
CustomStack(int maxSize) {
limit = maxSize;
}
void push(int x) {
if(s.size() < limit){
s.push(x);
}
}
int pop() {
if(s.empty()){
return -1;
}
int top = s.top();
s.pop();
return top;
}
void increment(int k, int val) {
while(!temp.empty()){
temp.pop();
}
while(!s.empty()){
temp.push(s.top());
s.pop();
}
int v;
while(!temp.empty() && k--){
v = temp.top();
temp.pop();
s.push(v + val);
}
while(!temp.empty()){
s.push(temp.top());
temp.pop();
}
}
};
// Runtime: 76 ms, faster than 8.00% of C++ online submissions for Design a Stack With Increment Operation.
// Memory Usage: 29.7 MB, less than 7.62% of C++ online submissions for Design a Stack With Increment Operation.
/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*/