标签:pac 方法 push 情况 run oid turn ast error
要求该栈的getMin方法和push和pop方法的时间复杂度都是O(1).
设计方案一:
package coding.chapter01; import java.util.Stack; /** * Created by Needle on 2017/3/17. */ public class GetMinStack { private Stack<int> dataStack;//存储数据的栈 private Stack<int> minStack;//存储最小值的栈 public GetMinStack(){ dataStack = new Stack<int>(); minStack = new Stack<int>(); } public int getMin(){ if (minStack.isEmpty()) throw new RuntimeException("The Stack is empty...."); else return minStack.peek();//获取栈顶元素的值,并不出栈 } public void push(int num){ //对minStack操作 if (minStack.isEmpty()) minStack.push(num); else if (num <= getMin()) minStack.push(num); //对dataStack进行操作 dataStack.push(num); } public int pop(){ if (minStack.isEmpty()) throw new RuntimeException("The Stack is empty...."); int value = dataStack.pop();//dataStack正常出栈 if (value == getMin())//minStack仅仅在于相等的情况下才出栈 minStack.pop(); return value; } }
设计方案二:
package coding.chapter01; import java.util.Stack; /** * Created by Needle on 2017/3/19. */ public class GetMinStack2 { private Stack<int> dataStack;//保存数据的栈 private Stack<int> minStack;//保存最小值的栈 public GetMinStack2(Stack<int> dataStack, Stack<int> minStack) { this.dataStack = dataStack; this.minStack = minStack; } //出栈 public int pop(){ if (dataStack.isEmpty()) throw new RuntimeException("Error: Stack is empty!"); int value = dataStack.pop(); minStack.pop(); return value; } public void push(int num){ dataStack.push(num); if(minStack.isEmpty()){ minStack.push(num); } else if(num <= minStack.peek()) minStack.push(num); else minStack.push(minStack.peek()); } public int GetMin2(){ if (minStack.isEmpty()) throw new RuntimeException("Error: Stack is empty!"); return minStack.peek(); } }
标签:pac 方法 push 情况 run oid turn ast error
原文地址:http://www.cnblogs.com/huoshaofeng/p/6582717.html