zoukankan      html  css  js  c++  java
  • 如何实现可以获取最小值的栈?

     CSDN官方图片

      我在某校研究生考试初试真题中见到了这个题目,这是一个非常有趣又有深度的问题,随即找到了这个问题的出处,在《剑指Offer》和LeetCode中均有该题,下面我贴一个CSDN官方给出的解题思路,循循渐进非常精彩

      CSDN【面试现场】如何实现获取最小值的栈?  

      以及LeetCode链接

      最小栈

      下面贴上自己改写的C++代码

      

    class MinStack {
    private :
        vector<int> data;
        vector<int> mins;
    
    public:
        /** initialize your data structure here. */
        MinStack() {
            
        }
        
        void push(int x) {     
            data.push_back(x);
            if (mins.empty()) {
                // 初始化mins
                mins.push_back(0);
            } 
            else {
                // 辅助栈mins push最小值的索引
                int min = getMin();
                if (x < min) {
                    mins.push_back(data.size() - 1);
                }
            }       
        }
        
        void pop() {
            // 栈空,抛出异常
            if (data.empty()) {
                throw "栈为空!";
            }
            // pop时先获取索引
            int popIndex = data.size() - 1;
            // 获取mins栈顶元素,它是最小值索引
            int minIndex = mins.at(mins.size() - 1);
            // 如果pop出去的索引就是最小值索引,mins才出栈
            if (popIndex == minIndex) {
                mins.pop_back();
            }
            data.pop_back();
        }
        
        int top() {
            // 栈空,抛出异常
            if (data.size() == 0) {
                throw "栈为空!";
            }
            return data.at(data.size() - 1);
        }
        
        int getMin() {
            // 栈空,抛出异常
            if (data.empty()) {
                throw "栈为空!";
            }
            // 获取mins栈顶元素,它是最小值索引
            int minIndex = mins.at(mins.size() - 1);
            return data.at(minIndex);
        }
    };
    
    /**
     * 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();
     */
  • 相关阅读:
    bzoj 4007
    bzoj 2190
    bzoj 2186
    bzoj 2005
    bzoj 2721
    bzoj 1951
    CF919F
    CF1005F
    CF1019C
    bitset用法详解
  • 原文地址:https://www.cnblogs.com/MK-XIAOYU/p/12631318.html
Copyright © 2011-2022 走看看