设计getMin功能的栈
设计getMin功能的栈
http://www.nowcoder.com/questionTerminal/c623426af02d4c189f92f2a99647bd34
实现一个特殊功能的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。
有三种操作种类,op1表示push,op2表示pop,op3表示getMin。你需要返回和op3出现次数一样多的数组,表示每次getMin的答案
1<=操作总数<=1000000
-1000000<=每个操作数<=1000000
数据保证没有不合法的操作
import java.util.*; public class Solution { /** * return a array which include all ans for op3 * @param op int整型二维数组 operator * @return int整型一维数组 */ Stack<Integer> allData; Stack<Integer> minData; public int[] getMinStack (int[][] op) { // write code here allData = new Stack<>(); minData = new Stack<>(); ArrayList<Integer> res = new ArrayList<>(); for (int[] option : op) { switch(option[0]) { case 1: push(option[1]); break; case 2: pop(); break; case 3: int min = getMin(); res.add(min); } }// for int[] result = new int[res.size()]; for (int i = 0; i < result.length; i++) { result[i] = res.get(i); } return result; } private void push(int num) { allData.push(num); if (!minData.isEmpty()) { minData.push((minData.peek() < num) ? minData.peek() : num); } else minData.push(num); } private void pop() { allData.pop(); minData.pop(); } private int getMin() { return minData.peek(); } }