【LeetCode-面试算法经典-Java实现】【155-Min Stack(最小栈)】
2015-08-21 06:30
627 查看
【155-Min Stack(最小栈)】
【LeetCode-面试算法经典-Java实现】【所有题目目录索引】
原题
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.
题目大意
设计一个栈,支持push,pop,top,和查找最小的元素操作(常量时间)解题思路
使用一个辅助栈来保存栈中的最小元素。代码实现
算法实现类public class MinStack { private final static int DEFAULT_SIZE = 1000; private int[] stack; private int[] minIndex; // 用于保存前n个数据的栈中最小元素的下标 private int min = Integer.MAX_VALUE; // 用于记录插入过程中的最小数据 private int index = -1; // 记录最小元素在stack中的位置 private int current = -1; public MinStack() { stack = new int[DEFAULT_SIZE]; minIndex = new int[DEFAULT_SIZE]; } public MinStack(int size) { stack = new int[size]; minIndex = new int[size]; } public void push(int x) { current++; // 移动到要插入的位置 if (current >= stack.length) { // 扩容 int[] tmp = new int[current * 2]; System.arraycopy(stack, 0, tmp, 0, stack.length); stack = tmp; tmp = new int[current * 2]; System.arraycopy(minIndex, 0, tmp, 0, minIndex.length); minIndex = tmp; } stack[current] = x; // 插入数据 if (x < min) { // 保存插入的最小值 min = x; index = current; // 记录[0, current]中最小的元素下标是index } minIndex[current] = index; } public void pop() { current--; if (current >= 0) { min = stack[minIndex[current]]; // 重新设置栈中的最小值 index = minIndex[current]; // 重置最小值的索引 } } public int top() { if (current < 0) { throw new RuntimeException("No more data"); } return stack[current]; } public int getMin() { if (current < 0) { throw new RuntimeException("No more data"); } return stack[minIndex[current]]; } }
评测结果
点击图片,鼠标不释放,拖动一段位置,释放后在新的窗口中查看完整图片。特别说明
欢迎转载,转载请注明出处【/article/1472852.html】
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【154-Find Minimum in Rotated Sorted Array II(找旋转数组中的最小数字II)】
- 【LeetCode-面试算法经典-Java实现】【153-Find Minimum in Rotated Sorted Array(找旋转数组中的最小数字)】
- 黑马程序员——Java基础---继承、抽象、接口(一)
- 黑马程序员——反射
- 黑马程序员_java基础学习IO流学习笔记
- 剑指Offer面试题:7.旋转数组的最小数字
- 程序员应该避免的5种代码注释
- 9秒学院:为什么程序员也能成为伟大的CEO
- 【面试题之算法部分】LIS最长递增子序列
- 每天五个java相关面试题(6)--jsp篇
- ios-面试
- 黑马程序员04面向对象概述
- 黑马程序员_Java集合框架
- 【面试题之算法部分】最长回文子串
- 黑马程序员03数组排序与二分法查找
- 黑马程序员02JAVA基础语法
- 面试题,凑14,将数组中相加为14的数去除,并升序排列
- 黑马程序员01JAVA概述
- 黑马程序员——Java基础---数组与集合之间转换
- 一个平庸程序员的自白