leetcode算法学习----155. 最小栈(MinStack )
2024-08-30 22:34:37
下面题目是LeetCode算法155题: https://leetcode.com/problems/min-stack/
题目1:最小函数min()栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
package com.good.good.study.stack; import java.util.Stack; /**
* ###155题.设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
* push(x) -- 将元素 x 推入栈中。
* pop() -- 删除栈顶的元素。
* top() -- 获取栈顶元素。
* min() -- 检索栈中的最小元素。
* @author monkjavaer
* @date 2018/09/11 21:44
*/
public class MinStack {
/**
* 真正存放数据栈
*/
public static Stack<Integer> stack = new Stack<>(); /**
* 存放最小数栈
*/
public static Stack<Integer> minStack = new Stack<>(); /**
* push 放入元素
* @param data
*/
public void push(int data) {
stack.push(data);
if (minStack.size()==0||data<minStack.peek()){
minStack.push(data);
}else {
minStack.push(minStack.peek());
}
} /**
* 获取栈顶元素
* @return
*/
public int top() {
return stack.peek(); } /**
* pop 推出元素
* @return
* @throws Exception
*/
public int pop() throws Exception {
minStack.pop();
return stack.pop();
} /**
* min 最小函数,调用该函数,可直接返回当前AntMinStack的栈的最小值
*
* @return
* @throws Exception
*/
public int min() throws Exception {
return minStack.peek();
} public static void main(String[] args){
MinStack antMinStack = new MinStack();
antMinStack.push(2);
antMinStack.push(1);
antMinStack.push(8);
antMinStack.push(9);
antMinStack.push(1);
try {
System.out.println("最小值:"+antMinStack.min());
antMinStack.pop();
antMinStack.pop();
System.out.println("最小值:"+antMinStack.min());
} catch (Exception e) {
e.printStackTrace();
} } }
最新文章
- POJ No.2386【B007】
- 李洪强iOS经典面试题131
- GWYAlertSelectView 选择收货地址和选择联系人
- 配置Java环境-20160613
- JMS笔记(二)
- 在sae配置django项目
- (大数据工程师学习路径)第三步 Git Community Book----中级技能(下)
- hadoop配置文件的作用
- 瞎j8封装第二版之数据层的封装
- 周一02.4变量&;垃圾回收机制
- LODOP不同电脑打印效果不同排查
- 操作系统实现线程的几种模式 和 java创建线程的3个方式
- 什么是 superset
- js判断字符串是否在数组中
- 微信小程序不能超过十个并发的解决办法
- spring整合strus2的Hellowworld
- linux内核配置 kbuild
- N-Queens I II(n皇后问题)(转)
- vue-cli生成的项目配置开发和生产环境不同的接口
- Caused by: java.lang.OutOfMemoryError: Failed to allocate a 29433932 byte allocation with 14683576 free bytes and 14MB