LeetCode-155. Min Stack

来源:互联网 发布:java物流管理系统 编辑:程序博客网 时间:2024/06/06 02:27

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.

可以维护一个最小值min,插入与删除时时更新该值。
当然删除时需要遍历整个列表

class MinStack {    private LinkedList<Integer> list;    private int min;    /** initialize your data structure here. */    public MinStack() {        list = new LinkedList<>();        min = Integer.MAX_VALUE;    }    public void push(int x) {        list.push(x);        if (x < min) {            min = x;        }    }    public void pop() {        list.pop();        min = Integer.MAX_VALUE;        for (int x : list) {            if (x < min) {                min = x;            }        }    }    public int top() {        return list.peek();    }    public int getMin() {        return min;    }}

或者,在插入时检查插入的元素是否比当前最小值小,如果小的话先把原来的最小值插入(保存插入该元素前的最小值)再更新最小值,在把当前元素插入进去。

public class MinStack {    private LinkedList<Integer> list;    private int min;    /** initialize your data structure here. */    public MinStack() {        list = new LinkedList<>();        min = Integer.MAX_VALUE;    }    public void push(int x) {        if (x <= min) {            list.push(min);            min = x;        }        list.push(x);    }    public void pop() {        if (min == list.pop()) {            min = list.pop();        }    }    public int top() {        return list.peek();    }    public int getMin() {        return min;    }    public LinkedList<Integer> getList() {        return list;    }}

又或者简单点,每次插入元素时现将该插入该元素之前的最小值插入进去。pop需要进行两次,第二次获得第一个pop后当前的最小值

class MinStack {        private LinkedList<Integer> list;        private int min;        /** initialize your data structure here. */        public MinStack() {            list = new LinkedList<>();            min = Integer.MAX_VALUE;        }        public void push(int x) {            list.push(min);            if (x < min) {                min = x;            }            list.push(x);        }        public void pop() {            list.pop();            min = list.pop();        }        public int top() {            return list.peek();        }        public int getMin() {            return min;        }        public LinkedList<Integer> getList() {            return list;        }    }
原创粉丝点击