Skip to content

Commit 24bfcc8

Browse files
committed
Added Min Stack
1 parent 6fe45a8 commit 24bfcc8

3 files changed

Lines changed: 84 additions & 0 deletions

File tree

‎java/SUMMARY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
* [Length of Last Word](string/length-of-last-word.md)
5858
* [栈和队列](stack-and-queue/README.md)
5959
* [栈](stack-and-queue/stack/README.md)
60+
* [Min Stack](stack-and-queue/stack/min-stack.md)
6061
* [Valid Parentheses](stack-and-queue/stack/valid-parentheses.md)
6162
* [Longest Valid Parentheses](stack-and-queue/stack/longest-valid-parentheses.md)
6263
* [Largest Rectangle in Histogram](stack-and-queue/stack/largest-rectangle-in-histogram.md)

‎java/code/min-stack.java‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Min Stack
2+
// Time Complexity: O(n), Space Complexity: O(1)
3+
class MinStack {
4+
public void push(int x) {
5+
s.push(x);
6+
int minValue = minStack.isEmpty() ? x :
7+
Math.min(minStack.peek(), x);
8+
minStack.push(minValue);
9+
}
10+
11+
public void pop() {
12+
s.pop();
13+
minStack.pop();
14+
}
15+
16+
public int top() {
17+
return s.peek();
18+
}
19+
20+
public int getMin() {
21+
return minStack.peek();
22+
}
23+
24+
private Stack<Integer> s = new Stack<>();
25+
private Stack<Integer> minStack = new Stack<>();
26+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
## Min Stack
2+
3+
4+
### 描述
5+
6+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
7+
8+
* `push(x)` -- Push element x onto stack.
9+
* `pop()` -- Removes the element on top of the stack.
10+
* `top()` -- Get the top element.
11+
* `getMin()` -- Retrieve the minimum element in the stack.
12+
13+
14+
### 分析
15+
16+
用两个栈,一个是真实的栈,另一个作为辅助栈,辅助栈每次 push 时,会把新元素跟当前栈顶元素进行比较,存入二者中较小的那个。
17+
18+
举个例子,对于序列 `18, 19, 21, 15, 17`, 两个栈依次`push`进去的元素是这样的:
19+
20+
* 真实栈,`18, 19, 21, 15, 17`
21+
* 辅助栈,`18, 18, 18, 15, 15`
22+
23+
具体过程是这样的,对于 `18`, 辅助栈是空的,直接push进去,当遇到`19`时,此时栈顶元素是`18`,二者中`18`较小,就把18插入,此时辅助栈中就有了两个`18`,当遇到`21`时,以此类推,还是插入`18`,遇到`15`时,栈顶元素是`18`,`15`较小,就把15压入,此时辅助栈中有3个`18`,1个`15`,当遇到`17`时,栈顶元素是`15`,二者中`15`是较小值,于是插入`15`,结束。
24+
25+
26+
### 代码
27+
28+
{% if book.java %}
29+
```java
30+
// Min Stack
31+
// Time Complexity: O(n), Space Complexity: O(1)
32+
class MinStack {
33+
public void push(int x) {
34+
s.push(x);
35+
int minValue = minStack.isEmpty() ? x :
36+
Math.min(minStack.peek(), x);
37+
minStack.push(minValue);
38+
}
39+
40+
public void pop() {
41+
s.pop();
42+
minStack.pop();
43+
}
44+
45+
public int top() {
46+
return s.peek();
47+
}
48+
49+
public int getMin() {
50+
return minStack.peek();
51+
}
52+
53+
private Stack<Integer> s = new Stack<>();
54+
private Stack<Integer> minStack = new Stack<>();
55+
}
56+
```
57+
{% endif%}

0 commit comments

Comments
 (0)