当前位置: 代码迷 >> 综合 >> 第一章 栈和队列(设计一个有getMin功能的栈)
  详细解决方案

第一章 栈和队列(设计一个有getMin功能的栈)

热度:24   发布时间:2023-10-11 12:34:01.0
题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
要求:1、pop、push、getMin 操作的时间复杂度都是 O(1)2、设计的栈类型可以使用现成的栈结构
实现思路:定义两个栈,stackData,保存栈的所有数据;stackMin,保存栈中的较小数据1、入栈操作a、数据直接压入 stackData 中b、当 stackMin 为空时,将数据压入;当数据小于等于 stackMin 栈顶元素时,将数据压入2、出栈操作a、stackData 弹出元素 Ab、如果元素 A 和 stackMin 栈顶元素相等,那么 stackMin 也弹出一位元素3、获取最小元素stackMin 栈顶元素即为当前栈中最小元素

public class MyStack {public Stack<Integer> stackData;public Stack<Integer> stackMin;public MyStack() {stackData = new Stack<Integer>();stackMin = new Stack<Integer>();}public void push(Integer value) {if (stackMin.isEmpty()) {stackMin.push(value);} else if (value < -stackMin.peek()) {stackMin.push(value);}stackData.push(value);}public Integer pop() {if (stackData.isEmpty()) {throw new NullPointerException("stack is empty");}Integer val = stackData.pop();if (val.equals(stackMin.peek())) {stackMin.pop();}return val;}public Integer getMin() {if (stackMin.isEmpty()) {throw new NullPointerException("stack is empty");}return stackMin.peek();}
}

  相关解决方案