设计getMin功能的栈
描述
实现一个特殊功能的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
解题
Solution
/**
* 设计getMin功能的栈
* 使用两个栈
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public static Stack<Integer> s =new Stack<Integer>();
public static Stack<Integer> min_s =new Stack<Integer>();
public int[] getMinStack(int[][] op){
ArrayList<Integer> res = new ArrayList<Integer>();//列表
for (int i = 0; i < op.length; i++) {
if (op[i][0] == 1){
s.push(op[i][1]);
if (min_s.empty()||min_s.peek()>=op[i][1]) min_s.push(op[i][1]);//入栈,取栈顶元素
}else if (op[i][0] == 2){
if (!s.empty()){
if (s.peek().equals(min_s.peek())) min_s.pop();//出栈
s.pop();
}
}else{
res.add(min_s.peek());
}
}
int[] arr = new int[res.size()];
for (int i = 0; i < res.size(); i++) {
arr[i] = res.get(i);//格式转换
}
return arr;
}
}