mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 155. Min Stack.md
This commit is contained in:
parent
774dc20d12
commit
ec02c248e6
31
155. Min Stack.md
Normal file
31
155. Min Stack.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# [155. Min Stack](https://leetcode.com/problems/min-stack/description/)
|
||||||
|
# 思路
|
||||||
|
实现最小栈,要求所有操作的时间复杂度都为O(1)。
|
||||||
|
可考虑用两个站S1、S2,S1就正常记录minStack的值,而S2的栈顶记录了当前Minstack的最小值。S2的更新规则见代码。
|
||||||
|
# C++
|
||||||
|
```
|
||||||
|
class MinStack {
|
||||||
|
private:
|
||||||
|
stack<int> s1;
|
||||||
|
stack<int> s2; // S2的栈顶记录了当前Minstack的最小值
|
||||||
|
public:
|
||||||
|
/** initialize your data structure here. */
|
||||||
|
MinStack() {
|
||||||
|
}
|
||||||
|
|
||||||
|
void push(int x) {
|
||||||
|
s1.push(x);
|
||||||
|
if (s2.empty() || x <= getMin()) s2.push(x); // 新来的x比getMin还小,说明是新的最小值,应该入栈S2
|
||||||
|
}
|
||||||
|
void pop() {
|
||||||
|
if (s1.top() == getMin()) s2.pop(); // 若pop掉了最小元素,则S2也应该pop一个
|
||||||
|
s1.pop();
|
||||||
|
}
|
||||||
|
int top() {
|
||||||
|
return s1.top();
|
||||||
|
}
|
||||||
|
int getMin() { // S2的栈顶记录了当前Minstack的最小值
|
||||||
|
return s2.top();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
```
|
Loading…
Reference in New Issue
Block a user