• [LeetCode] Min Stack


    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • getMin() -- Retrieve the minimum element in the stack.

    这道题神烦,总是超过内存限制,思路就是那个但是就是内存超了,不明觉历,拿到要用c数组?

    总之需要注意两点:

    1.每个操作都要O(1)

    2.pop了以后注意min的变化

    class MinStack {
    private:
        vector<int> min;
        vector<int> data;
    public:
        void push(int x) {
            data.push_back(x);
            if (min.size() == 0 || data[min.at(min.size()-1)] > x) {
                min.push_back((int)data.size()-1);
            }
        }
        
        void pop() {
            if (data.size()) {
                if (min.size() > 0 && min.at(min.size()-1) == data.size()-1) {
                    min.pop_back();
                }
                data.pop_back();
            }
        }
        
        int top() {
            if (data.size() > 0)
                return data.at(data.size()-1);
            return INT_MIN;
        }
        
        int getMin() {
            return data.at(min.at(min.size()-1));
        }
    };
  • 相关阅读:
    要搜索内容
    .net core 过滤器
    C# => 写法
    js 数组的forEach 函数
    .net core 下载文件 其他格式
    win10 1903 更改文字大小
    fetch 写法
    C# 匿名对象 增加属性
    ping —— 虚拟机
    selenium验证车贷计算器算法
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4092059.html
Copyright © 2020-2023  润新知