DEV Community

guang
guang

Posted on

leetcode 155 mini stack

i am so glad i figure it out by myself. at first i just used a minval to save the min val of the stack, but when the min val is popped, the code went wrong. then i try to use another variable to save the next min val, but if it is also popped, the same problem occurred. then i have to use a stack to save the correspond min val when the item is popped out. at last i use a history min stack to save the history min value when the min value is changed. so it start from the second item, in the solution, they save the min value for every item, then when the item is popped, the min stack also popped, and when get min value, just return the top of min stack, that's more clean.
i also thought about dictionary, save every item and correspond min value, but the remove and pop function of dictionary need key as parameters, so i give up this way, but just now i know in python3, there's also function to pop the last inserted item. and there seems also solution using this way, with one stack.

Top comments (0)