zoukankan      html  css  js  c++  java
  • 面试题03.02.栈的最小值 力扣题解

    声明:此解答转载他人,原题解https://leetcode-cn.com/problems/min-stack-lcci/solution/dan-bian-liang-biao-ji-dang-qian-zui-xiao-yuan-su-/,我学习后为了加深理解写了这篇
    题目描述
    请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。

    示例:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> 返回 -3.
    minStack.pop();
    minStack.top();      --> 返回 0.
    minStack.getMin();   --> 返回 -2.
    

    首先,必须支持的pushpop函数和找栈顶top的函数都很简单
    push

    void push(int x) {
        if(!_stack.empty()){
            _stack.push(x);
        }
    }
    

    pop

    void pop() {
        if(_stack.empty())
            return;
        else if(_min == _stack.top()){//下一个元素是下一个最小值
            _stack.pop();
        }
    }
    

    top

    int top() {
        return _stack.top();
    }
    

    但是题目又要说必须加上一个求最小值的函数getMin,所以我们需要一个记录最小值的变量_min_min的初始值为INT_MAX,我怎么就想不到呢,INT_MAX是 int 类型的最大值(2147483647)。

    所以完整代码如下:

    class MinStack {
    public:
        /** initialize your data structure here. */
        stack<int> _stack;
        int _min = INT_MAX;
        MinStack() {
            
        }
        
        void push(int x) {
            if(_min >= x){
                if(!_stack.empty()){
                    _stack.push(_min);
                }
                _min = x;
            }
            _stack.push(x);
        }
        
        void pop() {
            if(_stack.empty())
                return;
            if(_stack.size() == 1)
                _min = INT_MAX;
            else if(_min == _stack.top()){//下一个元素是下一个最小值
                _stack.pop();
                _min = _stack.top();
            }
            _stack.pop();
        }
        
        int top() {
            return _stack.top();
        }
        
        int getMin() {
            return _min;
        }
    };
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack* obj = new MinStack();
     * obj->push(x);
     * obj->pop();
     * int param_3 = obj->top();
     * int param_4 = obj->getMin();
     */
    
  • 相关阅读:
    【Linux】linux系统管理---好用的一些开源工具
    【转载】超级系统工具Sysdig,比 strace、tcpdump、lsof 加起来还强大
    Redis 主从复制
    Redis 持久化之RDB和AOF
    Redis 快速入门
    EasyUI 树菜单
    Nginx 搭建图片服务器
    vsftpd 安装
    Nginx 安装部署
    Mybatis3 快速入门
  • 原文地址:https://www.cnblogs.com/coding365/p/12872243.html
Copyright © 2011-2022 走看看