Old Wei wins the offer to take you to learn --- Brush title series (20 min contains the function stack)

20. The stack includes a function min

problem:

Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).
Note: to ensure that the test is not when the stack is empty, calls on the stack pop () or min () or top () method.

solve:

thought:

See this question, we initially might want to add a member variable to hold the smallest element, if every time you push the push element is smaller than the current smallest element, the smallest element is updated.
But this will be a problem, If the minimum element is pop it, how to get to the next smallest element of it? analysis can be found here, just add a member variable to store the smallest element is not enough, we also need to get the next smallest element in the minimum elements of pop, the second smallest after the pop-up, but also the times and to get small.
Therefore, with another stack to save these elements are an ideal fit. we call it the smallest element of the stack.
each time push operation, if push elements than the current the smallest element is smaller, put the element stack pressed into the smallest element, the smallest element of the original to become the next smallest elements. Similarly, when popped, the top element if the pop-up element and the smallest element stacks are equal, put the minimum top element of pop.

python code:

# -*- coding:utf-8 -*-

class Solution:
    def __init__(self):
        self.stack=[]
        self.minstack=[]
    def push(self, node):
        # write code here
        self.stack.append(node)
        if(not self.minstack or node < self.minstack[-1]):
            self.minstack.append(node)
    def pop(self):
        # write code here
        if(self.stack[-1]==self.minstack[-1]):
            self.minstack.pop()
        self.stack.pop()
        
    def top(self):
        # write code here
        return self.stack[-1]
    def min(self):
        # write code here
        return self.minstack[-1]
        
Published 160 original articles · won praise 30 · views 70000 +

Guess you like

Origin blog.csdn.net/yixieling4397/article/details/104920133