定义一种栈或队列,提供push、pop、getMin三种操作,要求平均复杂度O(1)。
最小栈
计算的是栈顶元素的最整个栈中的最小值,所以我们使用两个栈,一个存储原始数据,一个存储元素对应的最小值。在每次入栈时辅助栈将元素和站定元素比较,如果小于站定元素就入栈,否则压入栈顶元素。
class MinStack {
public:void push(int x) {if (st.empty()) {min_st.push(x);} else {min_st.push(min_st.top() < x ? min_st.top() : x);}st.push(x);}int pop() {int x = st.top();st.pop();min_st.pop();return x;}int getMin() {return min_st.top();}
private:std::stack<int> st;std::stack<int> min_st;
};
每个元素都被入栈和出栈一次,平均时间复杂度为Q(1)
最小队列
一个元素入队时,他前面比他小的元素不会影响他的最小值,但是他比前面元素小就影响了其那面元素的最小值。当元素入队时,如果之前元素的最小值比当前元素大就pop,把当前元素作为之前元素的最小值,所以符合单调递减栈的逻辑。
class MinQueue {
public:void push(int x) {qu.push(x);while (min_qu.size() && min_qu.back() > x) {// 当前元素影响之前的最小值min_qu.pop_back();}min_qu.push_back(x);}int pop() {int x = qu.front();if (x == min_qu.front()) {min_qu.pop_front();}qu.pop();return x;}int getMin() {return min_qu.front();}bool empty() {return qu.empty();}
private:std::queue<int> qu;std::deque<int> min_qu;
};
每个元素都被入栈和出栈一次,平均时间复杂度为Q(1)