|
7 | 7 | <p>Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.</p>
|
8 | 8 |
|
9 | 9 | <ul>
|
10 |
| - |
11 | 10 | <li>push(x) -- Push element x onto stack.</li>
|
12 |
| - |
13 | 11 | <li>pop() -- Removes the element on top of the stack.</li>
|
14 |
| - |
15 | 12 | <li>top() -- Get the top element.</li>
|
16 |
| - |
17 | 13 | <li>getMin() -- Retrieve the minimum element in the stack.</li>
|
18 |
| - |
19 | 14 | </ul>
|
20 | 15 |
|
21 | 16 | <p> </p>
|
@@ -51,13 +46,82 @@ minStack.getMin(); --> Returns -2.
|
51 | 46 | ### **Python3**
|
52 | 47 |
|
53 | 48 | ```python
|
| 49 | +class MinStack: |
| 50 | + |
| 51 | + def __init__(self): |
| 52 | + """ |
| 53 | + initialize your data structure here. |
| 54 | + """ |
| 55 | + self.s = [] |
| 56 | + self.helper = [] |
| 57 | + |
54 | 58 |
|
| 59 | + def push(self, x: int) -> None: |
| 60 | + self.s.append(x) |
| 61 | + element = x if not self.helper or x < self.helper[-1] else self.helper[-1] |
| 62 | + self.helper.append(element) |
| 63 | + |
| 64 | + def pop(self) -> None: |
| 65 | + self.s.pop() |
| 66 | + self.helper.pop() |
| 67 | + |
| 68 | + def top(self) -> int: |
| 69 | + return self.s[-1] |
| 70 | + |
| 71 | + def getMin(self) -> int: |
| 72 | + return self.helper[-1] |
| 73 | + |
| 74 | + |
| 75 | +# Your MinStack object will be instantiated and called as such: |
| 76 | +# obj = MinStack() |
| 77 | +# obj.push(x) |
| 78 | +# obj.pop() |
| 79 | +# param_3 = obj.top() |
| 80 | +# param_4 = obj.getMin() |
55 | 81 | ```
|
56 | 82 |
|
57 | 83 | ### **Java**
|
58 | 84 |
|
59 | 85 | ```java
|
60 |
| - |
| 86 | +class MinStack { |
| 87 | + |
| 88 | + private Deque<Integer> s; |
| 89 | + private Deque<Integer> helper; |
| 90 | + |
| 91 | + /** initialize your data structure here. */ |
| 92 | + public MinStack() { |
| 93 | + s = new ArrayDeque<>(); |
| 94 | + helper = new ArrayDeque<>(); |
| 95 | + } |
| 96 | + |
| 97 | + public void push(int x) { |
| 98 | + s.push(x); |
| 99 | + int element = helper.isEmpty() || x < helper.peek() ? x : helper.peek(); |
| 100 | + helper.push(element); |
| 101 | + } |
| 102 | + |
| 103 | + public void pop() { |
| 104 | + s.pop(); |
| 105 | + helper.pop(); |
| 106 | + } |
| 107 | + |
| 108 | + public int top() { |
| 109 | + return s.peek(); |
| 110 | + } |
| 111 | + |
| 112 | + public int getMin() { |
| 113 | + return helper.peek(); |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +/** |
| 118 | + * Your MinStack object will be instantiated and called as such: |
| 119 | + * MinStack obj = new MinStack(); |
| 120 | + * obj.push(x); |
| 121 | + * obj.pop(); |
| 122 | + * int param_3 = obj.top(); |
| 123 | + * int param_4 = obj.getMin(); |
| 124 | + */ |
61 | 125 | ```
|
62 | 126 |
|
63 | 127 | ### **...**
|
|
0 commit comments