题目

题目地址:https://leetcode-cn.com/problems/min-stack/

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

  • push(x) —— 将元素 x 推入栈中。
  • pop() —— 删除栈顶的元素。
  • top() —— 获取栈顶元素。
  • getMin() —— 检索栈中的最小元素。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.

提示:

  • poptopgetMin操作总是在非空栈上调用。

答案

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
package com.jarome.leetcode;

import java.util.ArrayList;
import java.util.List;

public class MinStack {

List<Integer> list = new ArrayList<>();

int min = Integer.MAX_VALUE;

public MinStack() {

}

public void push(int x) {
list.add(x);
min = Math.min(min, x);
}

public void pop() {
if (list.size() >= 1) {
Integer remove = list.remove(list.size() - 1);
if (remove <= min) {
// 移除的小于等于最小值,重新遍历寻找
min = Integer.MAX_VALUE;
for (Integer integer : list) {
min = Math.min(min, integer);
}
}
}
}

public int top() {
if (list.size() < 1) {
throw new RuntimeException("is empty");
}
return list.get(list.size() - 1);
}

public int getMin() {
if (list.size() < 1) {
throw new RuntimeException("is empty");
}
return min;
}

}