美文网首页皮皮的LeetCode刷题库
【剑指Offer】020——包含min函数的栈 (栈)

【剑指Offer】020——包含min函数的栈 (栈)

作者: 就问皮不皮 | 来源:发表于2019-08-18 23:02 被阅读0次

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数(时间复杂度应为O(1))。

解题思路

用一个栈stack保存数据,用另外一个栈temp保存依次入栈最小的数
比如,stack中依次入栈
5, 3, 4, 10, 2, 12, 1, 8
则temp依次入栈
5, 3, 3,3, 2, 2, 1, 1

每次入栈的时候,如果入栈的元素比min中的栈顶元素小或等于则入栈,否则用最小元素入栈。

参考代码

Java

import java.util.Stack;

public class Solution {
    Stack<Integer> stack = new Stack<>();
    Stack<Integer> help = new Stack<>();  // 辅助栈
    int min = Integer.MAX_VALUE;  //边界值
    public void push(int node) { // 压栈方法
        stack.push(node);
        // 获取最小值
        if (node < min) {
            help.push(node);
            min = node;
        } else {
            // 第一次入栈
            if (stack.isEmpty()) {
                min = node;
                help.push(node);
            } else {
                help.push(min); // 压入上一次的最小值
            }
        }
    }
    // 出栈方法
    public void pop() {
        if (stack.isEmpty()) {
            throw new RuntimeException("stack is none");
        } else { // 同时弹出
            stack.pop();
            help.pop();
        }
    }
    // 获取栈顶值
    public int top() {
        int t = stack.pop();
        help.pop();
        return t;

    }
    // 获取当前栈最小值
    public int min() {
        int m = help.pop();
        help.push(m);
        return m;
    }
}

Python

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack=[]
        self.helper = []
    def push(self, node):
        self.stack.append(node)
        # 判断为空
        if not self.helper or node <= self.helper[-1]:
            self.helper.append(node)
        else:
            self.helper.append(self.helper[-1])
    def pop(self):
        if self.stack:
            self.stack.pop()
            self.helper.pop()
    def top(self):
        return self.stack[-1]
    def min(self):
        return self.helper[-1]

个人订阅号

image

相关文章

网友评论

    本文标题:【剑指Offer】020——包含min函数的栈 (栈)

    本文链接:https://www.haomeiwen.com/subject/hitjsctx.html