下面题目是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();
} } }

  

  

 

最新文章

  1. POJ No.2386【B007】
  2. 李洪强iOS经典面试题131
  3. GWYAlertSelectView 选择收货地址和选择联系人
  4. 配置Java环境-20160613
  5. JMS笔记(二)
  6. 在sae配置django项目
  7. (大数据工程师学习路径)第三步 Git Community Book----中级技能(下)
  8. hadoop配置文件的作用
  9. 瞎j8封装第二版之数据层的封装
  10. 周一02.4变量&amp;垃圾回收机制
  11. LODOP不同电脑打印效果不同排查
  12. 操作系统实现线程的几种模式 和 java创建线程的3个方式
  13. 什么是 superset
  14. js判断字符串是否在数组中
  15. 微信小程序不能超过十个并发的解决办法
  16. spring整合strus2的Hellowworld
  17. linux内核配置 kbuild
  18. N-Queens I II(n皇后问题)(转)
  19. vue-cli生成的项目配置开发和生产环境不同的接口
  20. Caused by: java.lang.OutOfMemoryError: Failed to allocate a 29433932 byte allocation with 14683576 free bytes and 14MB

热门文章

  1. BFS(倒水问题) HDU 1495 非常可乐
  2. ACM_错排(递推dp)
  3. ACM_区间调度问题(贪心)
  4. gauge自动化测试框架(二)
  5. SQL数据库基础知识——抽象类
  6. FCC 基础JavaScript 练习6
  7. 我发现了新大陆--python的嵌入式开发
  8. Js上传图片并生成缩略图
  9. C# 创建与读写配置文件
  10. RabbitMQ系列(二)--基础组件