【LeetCode】Min Stack 解題報告,leetcodestack

來源:互聯網
上載者:User

【LeetCode】Min Stack 解題報告,leetcodestack

【題目】

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.
【用Java內建的Stack實現】

來自:https://oj.leetcode.com/discuss/15659/simple-java-solution-using-two-build-in-stacks?state=edit-15691&show=15659#q15659

class MinStack {    // stack: store the stack numbers    private Stack<Integer> stack = new Stack<Integer>();    // minStack: store the current min values    private Stack<Integer> minStack = new Stack<Integer>();    public void push(int x) {        // store current min value into minStack        if (minStack.isEmpty() || x <= minStack.peek())            minStack.push(x);        stack.push(x);    }    public void pop() {        // use equals to compare the value of two object, if equal, pop both of them        if (stack.peek().equals(minStack.peek()))            minStack.pop();        stack.pop();    }    public int top() {        return stack.peek();    }    public int getMin() {        return minStack.peek();    }}

【分析】

這道題的關鍵之處就在於 minStack 的設計,push() pop() top() 這些操作Java內建的Stack都有,不必多說。

我最初想著再弄兩個數組,分別記錄每個元素的前一個比它大的和後一個比它小的,想複雜了。

第一次看上面的代碼,還覺得它有問題,為啥只在 x<minStack.peek() 時壓棧?如果,push(5), push(1), push(3) 這樣minStack裡不就只有5和1,這樣pop()出1後, getMin() 不就得到5而不是3嗎?其實這樣想是錯的,因為要想pop()出1之前,3就已經被pop()出了。. 

minStack 記錄的永遠是當前所有元素中最小的,無論 minStack.peek() 在stack 中所處的位置。


【不用內建Stack的實現】

來自:https://oj.leetcode.com/discuss/15651/my-java-solution-without-build-in-stack

class MinStack {    Node top = null;    public void push(int x) {        if (top == null) {            top = new Node(x);            top.min = x;        } else {            Node temp = new Node(x);            temp.next = top;            top = temp;            top.min = Math.min(top.next.min, x);        }    }    public void pop() {        top = top.next;        return;    }    public int top() {        return top == null ? 0 : top.val;    }    public int getMin() {        return top == null ? 0 : top.min;    }}class Node {    int val;    int min;    Node next;    public Node(int val) {        this.val = val;    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.