zoukankan      html  css  js  c++  java
  • LeetCode 155. Min Stack

    这个题目的关键是要有一个最小值的私有变量,在入栈和出栈时检查一下最小值是否变化即可,就能实现返回最小值是在常数时间内

    不过题目的注释中是有错误的,因为用new得到的是一个指针,不能用.运算符而是用->运算符

    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.

    Example:

    MinStack minStack = new MinStack();
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    minStack.getMin();   --> Returns -3.
    minStack.pop();
    minStack.top();      --> Returns 0.
    minStack.getMin();   --> Returns -2.
    class MinStack {
    public:
        /** initialize your data structure here. */
        MinStack() {
            mytop = 0;
            min = INT32_MAX;
        }
    
        void push(int x) {
            ++mytop;
            myarray.insert(myarray.cend(),x);
            if (min > x)
                min = x;
        }
    
        void pop() {
            --mytop;
            if (min == myarray[mytop])
            {
                min=myarray[0];
                for(int i=1;i<mytop;++i)
                {
                    if(min>myarray[i])
                    min=myarray[i];
                }
            }
            if(mytop==0)
            min = INT32_MAX;
            myarray.erase(--myarray.end());
        }
    
        int top() {
            return myarray[mytop-1];
        }
    
        int getMin() {
            return min;
        }
    private:
        int mytop;
        int min;
        vector<int> myarray;
    };
    
    /**
     * 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();
     */
  • 相关阅读:
    Socket
    Cookie & Session
    一些快捷键&工具的用法收集
    过桥问题及一些想法
    微信初步开发(测试用)
    代码的编写习惯
    Python爬虫简单笔记
    如何降低AzurePaasSQL的表占用空间
    Sonar代码检测工具安装与使用及问题记录
    AzureDevops发布Artifact
  • 原文地址:https://www.cnblogs.com/csudanli/p/5747069.html
Copyright © 2011-2022 走看看