LeetCode.155 Min Stack

来源:互联网 发布:linux dma中断 编辑:程序博客网 时间:2024/06/03 21:16

题目:

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.
分析:

class MinStack {        Stack<Node> s;    /** initialize your data structure here. */    public MinStack() {        s = new Stack<Node>();    }        public void push(int x) {        Node newNode = new Node();        newNode.val = x;        if (this.s.isEmpty()) {            newNode.min = x;        } else {            //保证每次最上面的都是最小的元素            newNode.min = Math.min(s.peek().min, x);        }                s.push(newNode);    }        public void pop() {        this.s.pop();    }        public int top() {        return this.s.peek().val;    }        public int getMin() {        return this.s.peek().min;    }        public static class Node {        int val;        int min;    }}/** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x);-m */


原创粉丝点击