您的位置:首页 > 其它

Solution 2: Min Stack

2015-06-28 18:57 190 查看
问题描述

定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。

实现栈的push(), pop()及getMin()函数,要求函数的时间复杂度为O(1).

解决思路

使用两个栈,一个为普通栈,实现push和pop函数;另一个记录所有入栈元素的非递增序列;

如下图所示:



程序

public class MinStack {
private Stack<Integer> normal;
private Stack<Integer> min;

public MinStack() {
normal = new Stack<Integer>();
min = new Stack<Integer>();
}

public void push(int elem) {
normal.push(elem);
if (min.isEmpty() || min.peek() >= elem) {
min.push(elem);
}
}

public int pop() throws Exception {
if (normal.isEmpty()) {
throw new Exception("Error: The Stack is Empty!");
}
int res = normal.pop();
if (min.peek() == res) {
min.pop();
}
return res;
}

public int getMin() throws Exception {
if (min.isEmpty()) {
throw new Exception("Error: The Stack is Empty!");
}
return min.peek();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: