首页 > 其他 > 详细

LeetCode——Min Stack

时间:2018-02-20 18:57:48      阅读:242      评论:0      收藏:0      [点我收藏+]

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.
原题链接:https://oj.leetcode.com/problems/min-stack/
取出栈中的最小元素须要常数时间。
能够用两个栈来实现,当中一个栈存储的是所有的元素,而还有一个栈存储的是前一个栈中的最小元素,这样每次更新后一个栈就可以。
public class MinStack {
	private List<Integer> stack = new ArrayList<Integer>();
	private List<Integer> minstack = new ArrayList<Integer>();
	public void push(int x) {
		stack.add(x);
		if(minstack.isEmpty() || minstack.get(minstack.size()-1) >= x)
			minstack.add(x);
	}

	public void pop() {
		if(stack.isEmpty())
			return;
		int tmp = stack.remove(stack.size()-1);
		if(!minstack.isEmpty() && tmp == minstack.get(minstack.size()-1))
			minstack.remove(minstack.size()-1);
	}

	public int top() {
		if(!stack.isEmpty())
			return stack.get(stack.size()-1);
		return -1;
	}

	public int getMin() {
		if(!minstack.isEmpty())
			return minstack.get(minstack.size()-1);
		return -1;
	}
}




LeetCode——Min Stack

原文:https://www.cnblogs.com/zhchoutai/p/8455528.html

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