Retrieving the Min element in a stack in O(1) Time

后端 未结 3 1039
一生所求
一生所求 2021-02-06 09:33

The reason I\'m asking this question is because I cannot see why the way I think cannot be applied to this particular question

\"How would you design a stack which,

3条回答
  •  渐次进展
    2021-02-06 10:06

    This wouldn't work if you popped numbers off the stack.

    Ex. 2,4,5,3,1. After you pop 1 off, what is your minimum?

    The solution is to keep a stack of minimums, not just a single value. If you encounter a value that is less than equal to the current minimum, you need to push it onto the min-stack.

    Ex.

    Push(4):
    Stack: 4
    Min-stack: 4
    
    Push(2):
    Stack: 4 2
    Min-stack: 4 2
    
    Push(2):
    Stack: 4 2 2
    Min-stack: 4 2 2
    
    Push(5):
    Stack: 4 2 2 5
    Min-stack: 4 2 2
    
    Push(3):
    Stack: 4 2 2 5 3
    Min-stack: 4 2 2
    
    Push(1):
    Stack: 4 2 2 5 3 1
    Min-stack: 4 2 2 1
    
    Pop():
    Stack: 4 2 2 5 3
    Min-stack: 4 2 2
    
    Pop():
    Stack: 4 2 2 5
    Min-stack: 4 2 2
    
    Pop():
    Stack: 4 2 2
    Min-stack: 4 2 2
    
    Pop():
    Stack: 4 2
    Min-stack: 4 2
    
    Pop():
    Stack: 4
    Min-stack: 4
    

提交回复
热议问题