File tree 2 files changed +94
-0
lines changed 2 files changed +94
-0
lines changed Original file line number Diff line number Diff line change @@ -21,6 +21,10 @@ pop -- 返回并删除栈顶元素的操作。
21
21
22
22
[ Leetcode173 二叉搜索树迭代器] ( stack_queue/leetcode173.md )
23
23
24
+ [ Leetcode 155 最小栈] ( stack_queue/leetcode155.md )
25
+
26
+
27
+
24
28
25
29
26
30
Original file line number Diff line number Diff line change
1
+ ### 描述
2
+
3
+ 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
4
+
5
+ push(x) -- 将元素 x 推入栈中。
6
+ pop() -- 删除栈顶的元素。
7
+ top() -- 获取栈顶元素。
8
+ getMin() -- 检索栈中的最小元素。
9
+
10
+ 来源:力扣(LeetCode)
11
+ 链接:https://leetcode-cn.com/problems/min-stack
12
+
13
+ ### 思路
14
+
15
+ 其实这题的话,如果单纯考虑这样的需求,我们可能第一时间想到的是堆。
16
+
17
+ 这题我们还是思考一下,其实也不难。毕竟他的难度评判认定为简单。
18
+
19
+ 我们可以可以这么做:
20
+
21
+ 我们用两个标准栈,我们用一个栈来正常压栈,弹栈,另外一个栈,我们则需要维护一下大小关系了。假设A,B两个栈,A栈我们用来维护正常压栈弹栈,B栈则是最大的元素在栈底部,最小的元素在栈顶,那么我们就可以常数时间拿到最小元素了。我们这里用伪代码的形式写一下:
22
+
23
+ ```
24
+ 元素 E 压栈
25
+ A 压栈
26
+ 如果 B 栈是空 或者 B 栈栈顶元素比 E 大
27
+ B 压栈
28
+ 否则
29
+ B 压栈一个原来的栈顶元素
30
+ ```
31
+
32
+ 这样,我们就可以维护一个最小栈了。
33
+
34
+ ### 代码
35
+
36
+ 代码不会很复杂,见下面:
37
+
38
+ ``` java
39
+ class MinStack {
40
+ private Stack<Integer > stack; // A 栈
41
+ private Stack<Integer > helper; // B 栈
42
+
43
+ /* * initialize your data structure here. */
44
+ public MinStack () {
45
+ stack = new Stack ();
46
+ helper = new Stack ();
47
+ }
48
+
49
+ public void push (int x ) {
50
+ stack. add(x);
51
+ if (helper. isEmpty() || helper. peek() >= x) {
52
+ helper. add(x);
53
+ }else {
54
+ helper. add(helper. peek());
55
+ }
56
+ }
57
+
58
+ public void pop () {
59
+ if (! stack. isEmpty()) {
60
+ stack. pop();
61
+ helper. pop();
62
+ }
63
+ }
64
+
65
+ public int top () {
66
+ if (! stack. isEmpty()) {
67
+ return stack. peek();
68
+ }
69
+ throw new RuntimeException (" " );
70
+ }
71
+
72
+ public int getMin () {
73
+ if (! helper. isEmpty()) {
74
+ return helper. peek();
75
+ }
76
+ throw new RuntimeException (" " );
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Your MinStack object will be instantiated and called as such:
82
+ * MinStack obj = new MinStack();
83
+ * obj.push(x);
84
+ * obj.pop();
85
+ * int param_3 = obj.top();
86
+ * int param_4 = obj.getMin();
87
+ */
88
+ ```
89
+
90
+ 多思考,多学习。
You can’t perform that action at this time.
0 commit comments