Min Stack

来源:互联网 发布:mac管理员名称是什么 编辑:程序博客网 时间:2024/05/16 23:41

esign 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.
import java.util.Arrays;import java.util.Stack;public class Solution {public static void main(String[] args) {// TODO Auto-generated method stubMinStack minStack  = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);System.out.println(minStack.getMin());   minStack.pop();System.out.println(minStack.top());      System.out.println(minStack.getMin());}}class MinStack {    /** initialize your data structure here. */    Stack<Integer> stack;    int min = Integer.MAX_VALUE;//先设定最小值的初值为整型的最大值public MinStack() {        stack = new Stack<>();    }        public void push(int x) {    if(x<=min)    {    stack.push(min);//为什么要把之前的min也压入呢,这是为了防止pop的时候如果正好是最小值,则无法找到此时    //堆栈中的最小值了,所以以此来做个备份。    min = x;//新加入的x值比原先的min还小的时候,则更换最小值,并且把之前的min也加入stack中    }        stack.push(x);    }        public void pop() {    if(stack.peek() == min)    {    //当最上面那个数为最小值时,首先要先弹出最上面的数,然后再弹出之前push中被push进去的min值,与push成套    stack.pop();    min = stack.pop();    }else    stack.pop();    }        public int top() {    return stack.peek();        }        public int getMin() {    return min;    }}


0 0