【每日一题】力扣 115题最小栈

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2][]()

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

思路 :开辅助栈,我们可以在每个元素入栈时把当前栈的最小值存储起来。

代码

class MinStack {
public:
/** initialize your data structure here. */
stack <int> a_stack;//当前栈
stack <int> min_stack;//辅助栈
MinStack() {
min_stack.push(INT_MAX);//初始化;
}

void push(int x) {
a_stack.push(x);//入栈a
min_stack.push(min(min_stack.top(),x));//取比栈顶更小的值存入辅助栈
}

void pop() {
a_stack.pop();//出栈
min_stack.pop();//出栈
}

int top() {
return a_stack.top();//返回a的栈顶元素
}

int getMin() {
return min_stack.top();//返回辅助栈的最小元素
}
};

 

  

  

-------------------------------------------

个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!

如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

posted @ 2020-08-17 17:53  比尔的歌  阅读(118)  评论(0)    收藏  举报