-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 140 ms (5.17%), Space: 29.7 MB (10.33%) - LeetHub
- Loading branch information
1 parent
b2b3c5f
commit 38bf582
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
...-design-a-stack-with-increment-operation/1381-design-a-stack-with-increment-operation.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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); | ||
*/ |