栈——设计一个有getmin功能的栈
来源:互联网 发布:ubuntu查看opencv路径 编辑:程序博客网 时间:2024/06/05 07:14
题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
要求:
1、pop、push、getMin操作的时间复杂度都是O(1)。
2、设计的栈类型可以输用现成的栈结构。
思路:使用两个栈,一个用来保存栈中的元素,另一个用于保存每步的最小值
其实就是左神的思路啦~
代码:package getmin;import java.util.Stack;import javax.management.RuntimeErrorException;public class MyStack {private Stack<Integer> stackData;private Stack<Integer> stackMin;public MyStack(){this.stackData = new Stack<Integer>();this.stackMin = new Stack<Integer>();}public void push(int newNum){if(this.stackMin.isEmpty()){this.stackMin.push(newNum);}else if(newNum <= this.getmin()){this.stackMin.push(newNum);}else{this.stackData.push(newNum);}}public int pop(){if(this.stackData.isEmpty()){throw new RuntimeException("your stack is empty");}int value = this.stackData.pop();if(value == this.getmin()){this.stackMin.pop();}return value;}public int getmin(){if(this.stackMin.isEmpty()){throw new RuntimeException("your stack is empty");}return this.stackMin.peek();}public static void main(String args[]){MyStack sta = new MyStack();sta.push(3);sta.push(4);sta.push(2);sta.push(1);sta.pop();int min = sta.getmin();System.out.println(min);}}
阅读全文
0 0
- 栈——设计一个有getmin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有 getMin功能的栈
- 设计一个有getMin功能的栈
- 设计一个有getMin功能的栈
- 栈和队列——设计一个有getMin功能的栈(一)
- 栈和队列——设计一个有getMin功能的栈(二)
- 栈和队列 设计一个有getMin()功能的栈
- 如何移除解决方案中的TFS版本控制
- 【Codeforces 840 A. Leha and Function】& 构造
- JSON和JSONP,也许你会豁然开朗
- sql查询一个字段包含另一个字段内容
- 继承与面向对象设计
- 栈——设计一个有getmin功能的栈
- 【笨鸟先飞】android重新学习日记8---储存数据的方法
- python学习——Python3.x版本中filter(),map()函数的变化
- ZooKeeper学习第一期---Zookeeper简单介绍
- 模板与泛型编程
- McCabe环路复杂度计算
- 数据采集知识点总结
- :=的用法
- HDU