栈:leetcode 155

mac2025-10-29  15

LeetCode 155

最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) – 将元素 x 推入栈中。 pop() – 删除栈顶的元素。 top() – 获取栈顶元素。 getMin() – 检索栈中的最小元素。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/min-stack

思路

思路比较简单,建立两个栈即可。 特别注意push()中x进minstack栈时条件是<=

代码实现

import java.util.Stack; class MinStack { private Stack<Integer> stack; private Stack<Integer> minstack; /** initialize your data structure here. */ public MinStack() { stack= new Stack<>(); minstack =new Stack<>(); } public void push(int x) { if (minstack.isEmpty()||x<=minstack.peek()){ minstack.push(x); } stack.push(x); } public void pop() { int x=stack.pop(); if(x==minstack.peek()){ minstack.pop(); } } public int top() { return stack.peek(); } public int getMin() { return minstack.peek(); } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
最新回复(0)