Wins the Offer (XX): Contains min function stack
Search micro-channel public number: 'AI-ming3526' or 'this small computer vision' for more algorithms, machine learning, dry
CSDN: https://blog.csdn.net/baidu_31657889/
GitHub: https://github.com/ aimi-cn / AILearners
First, the primer
This series is my brush "to prove safety Offer" brush off the cattle in question notes online, it aims to enhance the ability under its own algorithm.
View the complete algorithm to prove safety issues resolved Offer Click: to prove safety Offer complete analytical exercises
Second, the title
Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).
1, ideas
In the case time complexity of 1, we can not use to traverse the stack, so we use the idea is to store a minimum value to the auxiliary stack
Stack 3,4,2,5,1
auxiliary stack 3,3,2,2,1
once, it is more the size of each stack and auxiliary stack, the stack if it is small, if the big push it to the current auxiliary stack top
when the stack, but also the auxiliary stack pop
this approach ensures that the auxiliary stack must have the minimum value to the current stack
2, programming
python2.7
Code implementation:
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.assist = []
def push(self, node):
min = self.min()
if not min or node < min:
self.assist.append(node)
else:
self.assist.append(min)
self.stack.append(node)
def pop(self):
if self.stack:
self.assist.pop()
return self.stack.pop()
def top(self):
# write code here
if self.stack:
return self.stack[-1]
def min(self):
# write code here
if self.assist:
return self.assist[-1]
AIMI-CN AI learning exchange group [1015286623] for more information on AI
Sharing technology, fun in life: our number of public computer vision this small push "AI" series News articles per week, welcome your interest!