Skip to content

Commit b635995

Browse files
committed
add q155
1 parent 4bca22a commit b635995

File tree

3 files changed

+77
-33
lines changed

3 files changed

+77
-33
lines changed

.idea/workspace.xml

Lines changed: 33 additions & 33 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@
5959

6060
* [q20_有效的括号](/src/栈相关/q20_有效的括号)
6161
* [q32_最长有效括号](/src/栈相关/q32_最长有效括号)
62+
* [q155_最小栈](/src/栈相关/q155_最小栈)
6263
* [q224_基本计算器](/src/栈相关/q224_基本计算器)
6364
* [q316_去除重复字母](/src/栈相关/q316_去除重复字母)
6465

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package 栈相关.q155_最小栈;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* 不使用辅助栈,每次push两个元素
7+
*/
8+
public class MinStack {
9+
10+
private Stack<Integer> stack;
11+
12+
public MinStack() {
13+
stack = new Stack<>();
14+
}
15+
16+
public void push(int x) {
17+
if (stack.isEmpty()) {
18+
stack.push(x);
19+
stack.push(x);
20+
} else {
21+
int tmp = stack.peek();
22+
stack.push(x);
23+
if (tmp < x) {
24+
stack.push(tmp);
25+
} else {
26+
stack.push(x);
27+
}
28+
}
29+
}
30+
31+
public void pop() {
32+
stack.pop();
33+
stack.pop();
34+
}
35+
36+
public int top() {
37+
return stack.get(stack.size() - 2);
38+
}
39+
40+
public int getMin() {
41+
return stack.peek();
42+
}
43+
}

0 commit comments

Comments
 (0)