zoukankan      html  css  js  c++  java
  • [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注册iis
    hdu 1081To The Max
    hdu 1312Red and Black
    hdu 1016Prime Ring Problem
    hdu 1159Common Subsequence
    hdu 1372Knight Moves
    hdu 1686Oulipo
    hdu 1241Oil Deposits
    hdu 1171Big Event in HDU
    hdu 4006The kth great number
  • 原文地址:https://www.cnblogs.com/agentgamer/p/4092059.html
Copyright © 2011-2022 走看看