LeetCode155. Min Stack
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.
设计一个栈,能做上面的内容,重点在于常数时间内获得栈中的最小值。
可以从头写一个栈,也可以使用标准stack来设计。
从头写一个的话,为了在常数时间内获得最小值,需要时时刻刻记录最小值,可以专门用一条链表来记载,head结点中保存最小值,如果来了一个不比最小值大的,就加在头的前面。在pop的时候要注意,如果栈顶元素的值与最小值相等的话,要舍弃最小值链的第一个值。
使用标准栈设计的话也差不多,需要一个栈来保存一路上获得的各个最小值,pop的时候minstack的第一个值如果与最小值栈相同,两个栈一起pop。
两种方法原理都是一样的。
还有一种是不需要两个链表或者两个栈的做法,做法是在栈中保存给定的x与最小值的差,具体写法还没有研究清楚,日后补上。