Lintcode12 Min Stack solution 題解

題目描述】

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

Notice:min operation will never be called if there is no number in the stack.

實現一個帶有取最小值min方法的棧,min方法將返回當前棧中的最小值。

你實現的棧將支持push,pop 和 min 操作,所有操作要求都在O(1)時間內完成。

注意:如果堆棧中沒有數字則不能進行min方法的調用

【題目鏈接】

http://www.lintcode.com/en/problem/min-stack/

【題目解析】

利用兩個棧結構,其中一個是主要的正常stack,滿足pop(), push()的O(1)時間要求,另外一個作爲輔助的minStack,僅存入min的integer。 min = Integer.parseInt(minStack.peek().toString());

push()時,如果number >= min,則push到minStack上 pop()時,如果number == min,也從minStack上pop

題中的例子,最終stack爲[2, 3, 1], minStack爲 [2, 1]

【答案鏈接】

http://www.jiuzhang.com/solutions/min-stack/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章