-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
56 lines (49 loc) · 1.27 KB
/
MinStack.java
File metadata and controls
56 lines (49 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.q0155;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Objects;
/**
* @author xjn
* @since 2020-05-31
* https://leetcode-cn.com/problems/min-stack/
* 155. 最小栈
* 时间复杂度O(1)
* 空间复杂度O(n)
*/
public class MinStack {
/**
* initialize your data structure here.
*/
private Deque<Integer> dataStack, minStack;
public MinStack() {
dataStack = new ArrayDeque<>();
minStack = new ArrayDeque<>();
}
public void push(int x) {
dataStack.push(x);
if (minStack.isEmpty() || x <= minStack.peek()) {
minStack.push(x);
}
}
public void pop() {
if (dataStack.isEmpty()) {
throw new RuntimeException("'Your stack is Empty");
}
Integer pop = dataStack.pop();
if (!minStack.isEmpty() && Objects.equals(pop, minStack.peek())) {
minStack.pop();
}
}
public int top() {
if (dataStack.isEmpty()) {
throw new RuntimeException("'Your stack is Empty");
}
return dataStack.peek();
}
public int getMin() {
if (minStack.isEmpty()) {
throw new RuntimeException("'Your stack is Empty");
}
return minStack.peek();
}
}