[leetcode] 155. Min Stack 解题报告

题目链接:https://leetcode.com/problems/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.

思路:用两个vector,一个用来存储栈的元素,另一个用来存储当前最小的值。用来存储当前最小值的vector是一个很有意思的技术,如果当前的数不小于上一个元素,则当前最小值应存储为上一个最小值。

代码如下:

class MinStack {
public:
    MinStack()
    {
        Min.push_back(INT_MAX);
    }
    void push(int x) {
        st.push_back(x);
        if(x < Min.back())
            Min.push_back(x);
        else
            Min.push_back(Min.back());
    }

    void pop() {
        st.erase(st.end()-1);
        Min.erase(Min.end()-1);
    }

    int top() {
        return st.back();
    }

    int getMin() {
        return Min.back();
    }
private:
    vector<int> st;
    vector<int> Min;
};

参考:https://leetcode.com/discuss/66983/c-o-1-solution

你可能感兴趣的:(LeetCode,算法,stack)