-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo30MinStack.java
More file actions
48 lines (40 loc) · 1.2 KB
/
No30MinStack.java
File metadata and controls
48 lines (40 loc) · 1.2 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
package com.wzx.sword;
import java.util.*;
/**
* @see <a href="https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/">https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/</a>
* @author wzx
*/
public class No30MinStack {
/**
* 单调栈
* <p>
* time: O(1)
* space: O(n)
*/
public static class MinStack {
private final Deque<Integer> stack;
private final Deque<Integer> minStack;
public MinStack() {
stack = new LinkedList<>();
minStack = new LinkedList<>();
}
public void push(int x) {
// 新加入的元素如果不比上一个状态的最小值小,那么这个元素对目前的最小值没有影响,不用添加
if (minStack.isEmpty() || minStack.peekFirst() >= x) minStack.addFirst(x);
stack.addFirst(x);
}
@SuppressWarnings("ConstantConditions")
public void pop() {
int popValue = stack.pollFirst();
if (popValue == minStack.peekFirst()) minStack.removeFirst();
}
@SuppressWarnings("ConstantConditions")
public int top() {
return stack.peekFirst();
}
@SuppressWarnings("ConstantConditions")
public int min() {
return minStack.peekFirst();
}
}
}