1.两个栈,栈A入栈,栈B存储与栈A实时变化中最小的元素
import java.util.*; public class Solution { Stack<Integer> stackA = new Stack<>(); //入栈的值存放在这 Stack<Integer> stackB = new Stack<>(); //存放最小的值 ArrayList<Integer> list = new ArrayList<>(); public int[] getMinStack (int[][] op) { for(int[] opt:op){ if(opt[0] == 1) push(opt[1]); //为1的时候 则为入栈 else if(opt[0] == 2) pop(); //为2的时候,出栈 else list.add(getMin()); } int[] res = new int[list.size()]; for(int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } public void push(int value){ stackA.push(value); if(stackB.isEmpty()) stackB.push(value); else{ if(value <= stackB.peek()){ stackB.push(value); } } } public void pop(){ int val = stackA.pop(); if(val == stackB.peek()) stackB.pop(); } public int getMin(){ return stackB.peek(); } }
2.一个栈+一个数组也能维护