mirror of
https://gitee.com/coder-xiaomo/leetcode-problemset
synced 2025-01-11 02:58:13 +08:00
54 lines
1.7 KiB
HTML
54 lines
1.7 KiB
HTML
|
<p>请你设计一个 <strong>最小栈</strong> 。它提供 <code>push</code> ,<code>pop</code> ,<code>top</code> 操作,并能在常数时间内检索到最小元素的栈。</p>
|
|||
|
|
|||
|
<p> </p>
|
|||
|
|
|||
|
<p>实现 <code>MinStack</code> 类:</p>
|
|||
|
|
|||
|
<ul>
|
|||
|
<li><code>MinStack()</code> 初始化堆栈对象。</li>
|
|||
|
<li><code>void push(int val)</code> 将元素val推入堆栈。</li>
|
|||
|
<li><code>void pop()</code> 删除堆栈顶部的元素。</li>
|
|||
|
<li><code>int top()</code> 获取堆栈顶部的元素。</li>
|
|||
|
<li><code>int getMin()</code> 获取堆栈中的最小元素。</li>
|
|||
|
</ul>
|
|||
|
|
|||
|
<p> </p>
|
|||
|
|
|||
|
<p><strong>示例 1:</strong></p>
|
|||
|
|
|||
|
<pre>
|
|||
|
<strong>输入:</strong>
|
|||
|
["MinStack","push","push","push","getMin","pop","top","getMin"]
|
|||
|
[[],[-2],[2],[-3],[],[],[],[]]
|
|||
|
|
|||
|
<strong>输出:</strong>
|
|||
|
[null,null,null,null,-3,null,2,-2]
|
|||
|
|
|||
|
<strong>解释:</strong>
|
|||
|
MinStack minStack = new MinStack();
|
|||
|
minStack.push(-2);
|
|||
|
minStack.push(2);
|
|||
|
minStack.push(-3);
|
|||
|
minStack.getMin(); --> 返回 -3.
|
|||
|
minStack.pop();
|
|||
|
minStack.top(); --> 返回 2.
|
|||
|
minStack.getMin(); --> 返回 -2.
|
|||
|
</pre>
|
|||
|
|
|||
|
<p> </p>
|
|||
|
|
|||
|
<p><strong> <br />
|
|||
|
提示:</strong></p>
|
|||
|
|
|||
|
<ul>
|
|||
|
<li><code>-2<sup>31</sup> <= val <= 2<sup>31</sup> - 1</code></li>
|
|||
|
<li><code>pop</code>、<code>top</code> 和 <code>getMin</code> 操作总是在 <strong>非空栈</strong> 上调用</li>
|
|||
|
<li><code>push</code>、<code>pop</code>、<code>top</code> 和 <code>getMin</code> 最多被调用 <code>3 * 10<sup>4</sup></code> 次</li>
|
|||
|
</ul>
|
|||
|
|
|||
|
<p> </p>
|
|||
|
|
|||
|
<p>注意:本题与主站 155 题相同:<a href="https://leetcode-cn.com/problems/min-stack/">https://leetcode-cn.com/problems/min-stack/</a></p>
|
|||
|
|
|||
|
<p> </p>
|