算法之设计一个有getMin方法的栈结构
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法之设计一个有getMin方法的栈结构相关的知识,希望对你有一定的参考价值。
要求该栈的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(); } }
以上是关于算法之设计一个有getMin方法的栈结构的主要内容,如果未能解决你的问题,请参考以下文章