一、题
描述
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) – 将元素 x 推入栈中。
- pop() – 删除栈顶的元素。
- top() – 获取栈顶元素。
- getMin() – 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解
1.粗糙
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
vector<int> c;
MinStack() {
}
void push(int x) {
s.push(x);
c.push_back(x);
}
void pop() {
s.pop();
c.pop_back();
}
int top() {
return s.top();
}
int getMin() {
int min = c[0];
for (int i = 1; i < c.size(); i++)
{
if (min > c[i])
{
min = c[i];
}
}
return min;
}
};
2.优化
算法的优化在于getMin()函数:寻找最小值时每次遍历一遍容器c太费时间。
可以使用记忆数组来优化,存放之前的结果。
class MinStack {
public:
/** initialize your data structure here. */
stack<int> s;
vector<int> c;
MinStack() {
}
void push(int x) {
s.push(x);
//空的话就入x;或者x比当前容器中的元素都小时入x
//引用尾部不用检查容器是否为空,因为c.empty()真就不判读c.back()
if (c.empty() || c.back()>x)
{
c.push_back(x);
}
else
{
c.push_back(c.back());
}
}
//弹出就都弹出
void pop() {
s.pop();
c.pop_back();
}
int top() {
return s.top();
}
//容器尾部就是最小值。
int getMin() {
return c.back();
}
};