码迷,mamicode.com
首页 > 其他好文 > 详细

Solution 2: Min Stack

时间:2015-06-28 20:05:05      阅读:109      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!