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();
     */
  • 相关阅读:
    js location.href ,location.replace, location.reload
    //js date对象常用方法
    js Math对象常用方法
    n sum
    two sum
    树:树中两个节点的最低公共祖先
    C++11:智能指针与lambda表达式
    回溯: 0-1背包
    动态库的soname实验
    DNS介绍与安装使用
  • 原文地址:https://www.cnblogs.com/csudanli/p/5747069.html
Copyright © 2011-2022 走看看