|
| 1 | +""" |
| 2 | +Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. |
| 3 | +
|
| 4 | +Implement the MinStack class: |
| 5 | +
|
| 6 | +MinStack() initializes the stack object. |
| 7 | +void push(int val) pushes the element val onto the stack. |
| 8 | +void pop() removes the element on the top of the stack. |
| 9 | +int top() gets the top element of the stack. |
| 10 | +int getMin() retrieves the minimum element in the stack. |
| 11 | +You must implement a solution with O(1) time complexity for each function. |
| 12 | +
|
| 13 | + |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +
|
| 17 | +Input |
| 18 | +["MinStack","push","push","push","getMin","pop","top","getMin"] |
| 19 | +[[],[-2],[0],[-3],[],[],[],[]] |
| 20 | +
|
| 21 | +Output |
| 22 | +[null,null,null,null,-3,null,0,-2] |
| 23 | +
|
| 24 | +Explanation |
| 25 | +MinStack minStack = new MinStack(); |
| 26 | +minStack.push(-2); |
| 27 | +minStack.push(0); |
| 28 | +minStack.push(-3); |
| 29 | +minStack.getMin(); // return -3 |
| 30 | +minStack.pop(); |
| 31 | +minStack.top(); // return 0 |
| 32 | +minStack.getMin(); // return -2 |
| 33 | + |
| 34 | +
|
| 35 | +Constraints: |
| 36 | +
|
| 37 | +-231 <= val <= 231 - 1 |
| 38 | +Methods pop, top and getMin operations will always be called on non-empty stacks. |
| 39 | +At most 3 * 104 calls will be made to push, pop, top, and getMin. |
| 40 | +""" |
| 41 | + |
| 42 | + |
1 | 43 | class MinStack:
|
2 | 44 |
|
3 | 45 | def __init__(self):
|
|
0 commit comments