Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 33fcdd1

Browse files
committed
移动155
1 parent 4fa954f commit 33fcdd1

File tree

2 files changed

+64
-38
lines changed

2 files changed

+64
-38
lines changed

‎leetcode/src/main/java/com/mistray/stack/MinStack.java

Lines changed: 0 additions & 38 deletions
This file was deleted.
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,77 @@
11
package com.mistray.stack;
22

3+
import java.util.Stack;
4+
35
/**
46
* @author ZJY(MistRay)
57
* @Project algorithm-study
68
* @Package com.mistray.stack
79
* @create 2020年05月21日 14:33
810
* @Desc
11+
* 设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
12+
*
13+
* push(x) —— 将元素 x 推入栈中。
14+
* pop() —— 删除栈顶的元素。
15+
* top() —— 获取栈顶元素。
16+
* getMin() —— 检索栈中的最小元素。
17+
*
18+
*
19+
* 示例:
20+
*
21+
* 输入:
22+
* ["MinStack","push","push","push","getMin","pop","top","getMin"]
23+
* [[],[-2],[0],[-3],[],[],[],[]]
24+
*
25+
* 输出:
26+
* [null,null,null,null,-3,null,0,-2]
27+
*
28+
* 解释:
29+
* MinStack minStack = new MinStack();
30+
* minStack.push(-2);
31+
* minStack.push(0);
32+
* minStack.push(-3);
33+
* minStack.getMin(); --> 返回 -3.
34+
* minStack.pop();
35+
* minStack.top(); --> 返回 0.
36+
* minStack.getMin(); --> 返回 -2.
37+
*
38+
*
39+
* 提示:
40+
*
41+
* pop、top 和 getMin 操作总是在 非空栈 上调用。
42+
*
943
*/
1044
public class MinStack155 {
1145

46+
private Stack<Integer> dataStack;
47+
private Stack<Integer> minStack;
48+
49+
// 思路:
50+
// 使用辅助栈的方式,让取最小值的时间复杂度保持在O(1)
51+
/** initialize your data structure here. */
52+
public MinStack155() {
53+
dataStack = new Stack<>();
54+
minStack = new Stack<>();
55+
}
56+
57+
public void push(int x) {
58+
dataStack.push(x);
59+
if (minStack.isEmpty() || minStack.peek() >= x){
60+
minStack.push(x);
61+
}
62+
}
63+
64+
public void pop() {
65+
if (dataStack.pop().equals(minStack.peek()) && minStack.size() > 1){
66+
minStack.pop();
67+
}
68+
}
69+
70+
public int top() {
71+
return dataStack.peek();
72+
}
1273

74+
public int getMin() {
75+
return minStack.peek();
76+
}
1377
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /