Use Java and Python to solve the problem: define the data structure of the stack. Please implement a min function in this type that can get the smallest element contained in the stack (time complexity should be O(1)).

Problem Description

To define the data structure of the stack, please implement a min function (time complexity should be O(1)) that can get the smallest element contained in the stack in this type.

Problem solving ideas

Idea: The stack saves data, the auxiliary stack saves the smallest number of
stacks in turn, and 6, 5, 8, 4, 3, 9
assist is pushed into the stack in turn, and 6, 5, 4, 3 are pushed into the stack
each time At the time, if the element pushed onto the stack is smaller than or equal to the top element in the stack, it will be pushed onto the stack, otherwise it will not be pushed onto the stack.

Code

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack = []    #数据栈
        self.assist = []   #辅助栈
    def push(self, node):
        # write code here
        min = self.min()             #得到栈中元素的最小值
        if min > node or not min:    #若待入栈的元素值小于栈中最小值或栈为空时
            self.stack.append(node)  #将这个元素分别压入数据栈和辅助栈
            self.assist.append(node)
        else:
            self.stack.append(node)  #否则只将这个元素压入数据栈
    def pop(self):
        # write code here
        if self.stack:
            if self.stack[-1] == self.assist[-1]:  #若数据栈和辅助栈的栈顶的元素值相等
                self.stack.pop()                   #则分别将这两个栈的栈顶元素弹出
                self.assist.pop()
            else:
                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] #返回辅助栈顶层元素,即最小值

    Stack<Integer> stackTotal = new Stack<Integer>();
    Stack<Integer> stackLittle = new Stack<Integer>();
 
    public void push(int node) {
    
    
        stackTotal.push(node);
        if(stackLittle.empty()){
    
    
            stackLittle.push(node);
        }else{
    
    
            if(node <= stackLittle.peek()){
    
    
                stackLittle.push(node);
            }else{
    
    
                stackLittle.push(stackLittle.peek());
            }
        }
    }
 
    public void pop() {
    
    
        stackTotal.pop();
        stackLittle.pop();
    }
 
    public int top() {
    
    
        return stackTotal.peek();
    }
 
    public int min() {
    
    
        return stackLittle.peek();
    }

Guess you like

Origin blog.csdn.net/weixin_44285445/article/details/108552247