【題目描述】
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.
實(shí)現(xiàn)一個(gè)帶有取最小值min方法的棧,min方法將返回當(dāng)前棧中的最小值。
你實(shí)現(xiàn)的棧將支持push,pop 和 min 操作,所有操作要求都在O(1)時(shí)間內(nèi)完成。
注意:如果堆棧中沒有數(shù)字則不能進(jìn)行min方法的調(diào)用
【題目鏈接】
http://www.lintcode.com/en/problem/min-stack/
【題目解析】
利用兩個(gè)棧結(jié)構(gòu),其中一個(gè)是主要的正常stack,滿足pop(), push()的O(1)時(shí)間要求,另外一個(gè)作為輔助的minStack,僅存入min的integer。 min = Integer.parseInt(minStack.peek().toString());
push()時(shí),如果number >= min,則push到minStack上 pop()時(shí),如果number == min,也從minStack上pop
題中的例子,最終stack為[2, 3, 1], minStack為 [2, 1]
【答案鏈接】