Title Description
To define the data structure of the stack, implement a min function in the type that can get the smallest element contained in the stack (the time complexity should be O (1)).
Title Address
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49?tpId=13&tqId=11173&rp=3&ru=/ta/ Coding-interviews&qru=/ta/coding-interviews/question-ranking
Ideas
Use two stacks, one for the data stack and one for the secondary stack. The data stack is used to store all data, and the secondary stack is used to store the minimum value.
As an example:
Into the stack: first into the empty digital stack into the number 3, obviously now 3 is the minimum value, we also put the minimum value into the auxiliary stack. Next press in the number 4, because 4 is greater than the previous minimum value, so we just need to enter the data stack, do not press into the auxiliary stack.
When the stack is out: when the data stack and the auxiliary stack are the same, the stack top elements of the auxiliary stack and the data stack are stacked, otherwise, only the stack top element of the data stack is stacked.
When getting the top element of the stack: returns the stack top element of the data stack directly
Stack smallest element: Returns the top element of the auxiliary stack directly
Python
#-*-coding:utf-8-*-classSolution:def __init__(self): Self.datastack=[] Self.minstack= [] defpush (self, node):#Write code hereself.dataStack.append (node)ifLen (self.minstack) <= 0orNode < self.minstack[-1]: Self.minStack.append (node)defpop (self):#Write code hereval =Self.dataStack.pop ()ifval = = Self.minstack[-1]: Self.minStack.pop ()returnValdefTop (self):#Write code here returnSelf.datastack[-1] defmin (self):#Write code here returnSelf.minstack[-1]if __name__=='__main__': Result=solution () Result.push (2) Result.push (4) Result.push (1) Result.push (3) Result.pop () Result.top () result.min ( )
The sword refers to offer 20. Stack (stack) containing the Min function