package com.fiberhome.monitor.task; import java.util.Stack; public class SolutionStack { private Stack<Integer> stack = new Stack<Integer>();//所有的值都进入这个栈 private Stack<Integer> minStack = new Stack<Integer>();//最小值栈,降序排 private Stack<Integer> maxStack = new Stack<Integer>();//最大值栈.,升序排 public void push(int node) { stack.push(node);//不管什么值,都入栈 if(maxStack.isEmpty() || minStack.isEmpty()){//如果大小栈为空,统一入栈 maxStack.push(node); minStack.push(node); }else{ if(node <= minStack.peek()){//比小栈最小的还小,压入小栈 minStack.push(node); }else if(node >= maxStack.peek()){//比大栈最大的还大,压入大栈 maxStack.push(node); } } } public void pop() { if(stack.peek()==minStack.peek()){//需要弹出的值=最小值的顶端值,最小栈也应弹出 minStack.pop(); }else if(stack.peek() == maxStack.peek()){//需要弹出的值=最大值的顶端值,最大栈也应弹出 maxStack.pop(); } stack.pop();//值栈弹出 } public int top() { return stack.peek(); } public int min() { return minStack.peek(); } public static void main(String[] args) { SolutionStack stack = new SolutionStack(); stack.push(5); stack.push(3); stack.push(7); stack.push(4);stack.push(2);stack.push(9);stack.push(1); int i = stack.min(); System.out.println(i); } }
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
最新推荐文章于 2024-04-12 16:19:06 发布