[LeetCode] Min Stack

來源:互聯網
上載者:User

標籤:

Question:

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.

1、題型分類:

2、思路:

  這道題需要實現一個能夠擷取最小值的棧,可以想到的必然是要麼每次通過遍曆擷取,要麼空間換時間,建立一個資料結構儲存這些有序最小值。剛開始一直沒有想過用Stack去實現這個功能,想到的是利用List去進行有序儲存,但是這樣每次插入的時間複雜度都不低,另外還有刪除操作,沒法實現題目的要求。現在希望一個資料結構,資料有序且從頂至下由小到大且能夠包含所有的元素,這樣就能夠與Stack並行操作了,但是實現想不出來這樣的結構。再去考慮這道題目的關鍵,getMin擷取最小值,但不需要刪除,那麼我們可以儲存插入進來的小於當前最小值的數值,,而且這個順序還必須和Stack裡面數的順序一致,那麼最後還是需要使用Stack,問題來了,刪除怎麼辦?由於順序一致,只要兩個棧頂部資料相同就刪除。如:

  

 

3、時間複雜度:

4、代碼:

class MinStack {    Stack<Integer> stack=new Stack<Integer>();    Stack<Integer> minStack=new Stack<Integer>();    public void push(int x) {        stack.push(x);        if(minStack.isEmpty() || (!minStack.isEmpty() && x<=minStack.peek()))            minStack.push(x);    }    public void pop() {        if(!stack.isEmpty())        {            if(!minStack.isEmpty() && minStack.peek().intValue()==stack.peek().intValue())                minStack.pop();            stack.pop();        }    }    public int top() {        return stack.peek();    }    public int getMin() {        if(!minStack.isEmpty())            return minStack.peek();        return 0;    }}

 

5、最佳化:

6、擴充:

[LeetCode] Min Stack

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.