设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
GetMin() – 检索栈中的最小元素。
解题思路:定义两个栈,其中m_data存储进栈元素,m_min存储最小栈。
进栈:
若最小栈为空,则将要进栈的元素直接压进最小栈;
若最小栈不为空,将进来元素与最小栈栈顶进行对比,若进来的元素比最小栈栈顶元素小,则进入最小栈。
出栈:
若出栈元素与最小栈栈顶元素相等,则最小栈出栈。
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
class MinStack{
stack<int> m_data;
stack<int> m_min;
public:
void push(int x){
m_data.push(x);
if (m_min.empty() || m_min.top() > x){
m_min.push(x);
}
}
void pop(){
if (m_data.top() == m_min.top()){
m_min.pop();
}
m_data.pop();
}
int top(){
return m_data.top();
}
int GetMin(){
return m_min.top();
}
};
int main(){
MinStack s1;
s1.push(5);
cout << s1.GetMin() << endl;
s1.push(4);
cout << s1.GetMin() << endl;
s1.push(6);
cout << s1.GetMin() << endl;
s1.push(2);
cout << s1.GetMin() << endl;
s1.push(1);
cout << s1.GetMin() << endl;
s1.push(9);
cout << s1.GetMin() << endl;
system("pause");
return 0;
}