设计得到最小值的栈
设计getMin功能的栈
http://www.nowcoder.com/questionTerminal/c623426af02d4c189f92f2a99647bd34
有两种方法:
一是只使用一个栈,栈里存储的是一个数组,保存最小值和当前值,最小值是在push时候判断的。
public class Solution { /** * return a array which include all ans for op3 * @param op int整型二维数组 operator * @return int整型一维数组 */ //只利用一个栈保存最小值和当前值 Stack<int[]> stack = new Stack<>(); ArrayList<Integer> list = new ArrayList<>(); public int[] getMinStack (int[][] op) { // write code here for(int[] opt : op){ if(opt[0] == 1) push(opt[1]); else if(opt[0] == 2) pop(); 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){ if(stack.isEmpty()){ stack.push(new int[]{value, value}); }else{ stack.push(new int[]{value, Math.min(value, stack.peek()[1])}); } } public void pop(){ stack.pop(); } public int getMin(){ return stack.peek()[1]; } }
二是利用多一个栈来存储最小值。
public class Solution { /** * return a array which include all ans for op3 * @param op int整型二维数组 operator * @return int整型一维数组 */ //只利用一个栈保存最小值和当前值 Stack<Integer> stackMin = new Stack<>(); Stack<Integer> stackCur = new Stack<>(); ArrayList<Integer> list = new ArrayList<>(); public int[] getMinStack (int[][] op) { // write code here for(int[] opt : op){ if(opt[0] == 1) push(opt[1]); else if(opt[0] == 2) pop(); 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){ stackCur.push(value); if(stackMin.isEmpty() || value < stackMin.peek()){ stackMin.push(value); } } public void pop(){ int cur = stackCur.pop(); if(!stackMin.isEmpty() && cur == stackMin.peek()){ stackMin.pop(); } } public int getMin(){ return stackMin.peek(); } }