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)); } };