力扣:155:最小栈

This commit is contained in:
huangge1199 2021-03-31 15:33:29 +08:00
parent 42c1bb2db3
commit c0f0e285da
2 changed files with 132 additions and 0 deletions

View File

@ -0,0 +1,93 @@
//设计一个支持 push pop top 操作并能在常数时间内检索到最小元素的栈
//
//
// push(x) 将元素 x 推入栈中
// pop() 删除栈顶的元素
// top() 获取栈顶元素
// getMin() 检索栈中的最小元素
//
//
//
//
// 示例:
//
// 输入
//["MinStack","push","push","push","getMin","pop","top","getMin"]
//[[],[-2],[0],[-3],[],[],[],[]]
//
//输出
//[null,null,null,null,-3,null,0,-2]
//
//解释
//MinStack minStack = new MinStack();
//minStack.push(-2);
//minStack.push(0);
//minStack.push(-3);
//minStack.getMin(); --> 返回 -3.
//minStack.pop();
//minStack.top(); --> 返回 0.
//minStack.getMin(); --> 返回 -2.
//
//
//
//
// 提示
//
//
// poptop getMin 操作总是在 非空栈 上调用
//
// Related Topics 设计
// 👍 856 👎 0
package leetcode.editor.cn;
import java.util.Stack;
//155:最小栈
public class MinStack {
public static void main(String[] args) {
//测试代码
// Solution solution = new MinStack().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class MinStack {
Stack<Integer> stack;
Stack<Integer> min;
public MinStack() {
stack = new Stack<>();
min = new Stack<>();
}
public void push(int val) {
if (stack.isEmpty()) {
min.push(val);
} else {
min.push(Math.min(min.peek(),val));
}
stack.push(val);
}
public void pop() {
stack.pop();
min.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,39 @@
<p>设计一个支持 <code>push</code> <code>pop</code> <code>top</code> 操作,并能在常数时间内检索到最小元素的栈。</p>
<ul>
<li><code>push(x)</code> &mdash;&mdash; 将元素 x 推入栈中。</li>
<li><code>pop()</code>&nbsp;&mdash;&mdash; 删除栈顶的元素。</li>
<li><code>top()</code>&nbsp;&mdash;&mdash; 获取栈顶元素。</li>
<li><code>getMin()</code> &mdash;&mdash; 检索栈中的最小元素。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong>
[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]
[[],[-2],[0],[-3],[],[],[],[]]
<strong>输出:</strong>
[null,null,null,null,-3,null,0,-2]
<strong>解释:</strong>
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --&gt; 返回 -3.
minStack.pop();
minStack.top(); --&gt; 返回 0.
minStack.getMin(); --&gt; 返回 -2.
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>pop</code><code>top</code><code>getMin</code> 操作总是在 <strong>非空栈</strong> 上调用。</li>
</ul>
<div><div>Related Topics</div><div><li></li><li>设计</li></div></div>\n<div><li>👍 856</li><li>👎 0</li></div>