Title Description
Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).
Problem-solving ideas
Stack comprising the min function
push stack, pop, min operation time complexity is O (1)
using aAuxiliary stackSave a minimum
Code
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.minval = []
def push(self, node):
self.stack.append(node)
min = self.min() # 使用一个辅助栈来保存最小值
if min and min < node:
self.minval.append(min)
else:
self.minval.append(node)
def pop(self):
if self.stack:
self.minval.pop()
return self.stack.pop()
return None
def top(self):
# write code here
if self.stack:
return self.stack[-1]
def min(self):
# write code here
if self.minval:
return self.minval[-1]
if __name__ == '__main__':
s = Solution()
s.push(7)
s.push(6)
s.push(3)
s.pop()
s.push(2)
print(s.stack)
print(s.min())
Output Example
[7,6,2]
2