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.
Solution

Original thinking is to use two stacks, one to store input elements, and the other is to store current min value.

However, there is an improvement that only use one stack.

This stack is to store diff between input value and current min value.

if current value < min value, we set min as current imput value.

Therefore, when we pop or peek each element in stack, we know:

If it‘s greater than 0, then it must be greater than current min value.

If it‘s smaller than 0, then it must equal to current min value.

 1 class MinStack { 2     Stack<Long> diff; 3     private long min; 4      5     public MinStack() { 6         min = Integer.MAX_VALUE; 7         diff = new Stack<Long>(); 8     } 9     public void push(int x) {10         diff.push((long)x - min);11         min = x < min? x : min;12     }13     public void pop() {14         if (diff.size() < 1)15             return;16         long tmp = diff.pop();17         if (tmp < 0)18             min -= tmp;19     }20     public int top() {21         long tmp = diff.peek();22         if (tmp < 0)23             tmp = min;24         else25             tmp += min;26         return (int)tmp;27     }28     public int getMin() {29         return (int)min;30     }31 }

 

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.