155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
Example:MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);
minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
题目含义:设计一个最小栈,push, pop, top, 和 getMin 方法都是常量时间
方法一:使用辅助栈
首先需要一个正常栈normal,用于栈的正常操作,然后需要一个辅助栈minval,专门用于获取最小值,具体操作如下。
import java.util.Stack; public class Solution { private Stack<Integer> values = new Stack<>(); private Stack<Integer> miniStack = new Stack<>(); public void push(int node) { values.push(node); if (miniStack.isEmpty()) miniStack.push(node); else miniStack.push(Math.min(miniStack.peek(), node)); } public void pop() { if (values.isEmpty()) return; values.pop(); miniStack.pop(); } public int top() { return values.peek(); } public int min() { return miniStack.peek(); } }
方法二:
1 class MinStack { 2 3 private Queue<Integer> p = new LinkedList<>(); 4 private Integer minValue = Integer.MAX_VALUE; 5 6 /** Initialize your data structure here. */ 7 public MinStack() { 8 } 9 10 public int getMin() { 11 12 for (int i=0;i<p.size();i++) 13 { 14 Integer value = p.poll(); 15 minValue = Math.min(minValue,value); 16 p.add(value); 17 } 18 return minValue; 19 } 20 21 /** Push element x onto stack. */ 22 public void push(int x) { 23 p.add(x); 24 for (int i=1;i<p.size();i++) 25 { 26 p.add(p.poll()); 27 } 28 } 29 30 /** Removes the element on top of the stack and returns that element. */ 31 public int pop() { 32 return p.poll(); 33 } 34 35 /** Get the top element. */ 36 public int top() { 37 return p.peek(); 38 } 39 40 /** Returns whether the stack is empty. */ 41 public boolean empty() { 42 return p.isEmpty(); 43 } 44 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!