Wins the offer - O (1) time complexity stack implemented min () function

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)).

ps: the test when the stack is not empty when, on the call stack pop () or min () or top () method.

Thinking

Dual-stack, is a common memory, the other is used to store a minimum value.

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack = []
        self.ministack = []
    def push(self, node):
        if len(self.ministack)>0:
            if node <= self.ministack[-1]:
                self.ministack.append(node)
            self.stack.append(node)
        else:
            self.ministack.append(node)
            self.stack.append(node)
    def pop(self):
        node = self.stack.pop()
        if node == self.ministack[-1]:
            self.ministack.pop()
        return node
    def top(self):
        return self.stack[-1]
    def min(self):
        return self.ministack[-1]

Stack had hit a big nod, afraid of careless use of the index

Published 82 original articles · won praise 2 · Views 4367

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/104745007