首页 > 其他 > 详细

Solution 2: Min Stack

时间:2015-06-28 20:02:36      阅读:257      评论:0      收藏:0      [点我收藏+]

问题描述

定义栈的数据结构,要求添加一个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();
	}
}

 

Solution 2: Min Stack

原文:http://www.cnblogs.com/harrygogo/p/4605949.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!