1. 程式人生 > >【leetcode】155. Min Stack

【leetcode】155. Min Stack

con supports 直接 pop retrieve out trie str tips

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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

Tips:
本題主要想實現求棧中最小值。使用兩個棧,其中一個為基本棧,另外一個用於保存最小值。
保存最小值的棧的操作思路如下:
push():當棧為空,或者即將壓入的數字小於minstack的棧頂時,執行壓入操作。
pop():當要彈出的數字,正好等於minstack棧頂的時候才彈出minStack的棧頂。
getMin():直接返回minstack的棧頂即可。
package easy;

import java.util.Stack;

public class L155MinStack {

	Stack<Integer> stack = new Stack<Integer>();
	Stack<Integer> minstack = new Stack<Integer>();

	public void push(int x) {
		stack.push(x);
		System.out.println(" stack push:"+x);
		if (minstack.isEmpty() || x <= minstack.peek()) {
			minstack.push(x);
			System.out.println("minstack push:"+x);
		}
	}

	public void pop() {
		int x = stack.peek();
		stack.pop();
		System.out.println("stack Pop:" + x);
		if (x == minstack.peek()) {
			minstack.pop();
			System.out.println("Minstack Pop:" + x);
		}
	}

	public int top() {
		System.out.println("peek" + stack.peek());
		return stack.peek();

	}

	public int getMin() {
		System.out.println("minStack peek" + minstack.peek());
		return minstack.peek();
	}

	public static void main(String[] args) {
		L155MinStack obj = new L155MinStack();
		obj.push(2);
		obj.push(1);
		obj.push(3);
		obj.push(4);
		obj.pop();
		obj.top();
		
	}
}

【leetcode】155. Min Stack