1. 程式人生 > >LeetCode——Min Stack

LeetCode——Min Stack

constant imu 兩個棧 csdn ons ews -s tps edit

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