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 50 51 52
| public class Solution { Stack<Integer> stack = new Stack<>(); Stack<Integer> min = new Stack<>(); Stack<Integer> temp = new Stack<>(); int top = -1; public void push(int node) { top = node; stack.push(node); if(min.isEmpty()){ min.push(node); }else{ while(!min.isEmpty()){ int top = min.pop(); if(top>node){ min.push(top); min.push(node); break; }else{ if(min.isEmpty()){ min.push(node); min.push(top); break; }else{ temp.push(top); } } } while(!temp.isEmpty()){ min.push(temp.pop()); } } } public void pop() { int temp = stack.pop(); top = stack.pop(); stack.push(top); min.remove( min.indexOf(temp)); } public int top() { return top; } public int min() { int result = min.pop(); min.push(result); return result; } }
|