求栈的最小值时间复杂度为O(1)

思路就是定义两个栈 一个专门存放最小值 一个存放数据
当入栈数据时  同时也要与最小栈中的数据比较一下  然后放入最小值的栈

具体的代码为:

package com.qbsea.arithmetic.stack;

import java.util.Stack;

public class GetMinStack_1 {
	private Stack<Integer> stackData = new Stack<>();
	private Stack<Integer> stackMin = new Stack<>();

	public void push(int newNum) {
		if (stackMin.isEmpty()) {
			stackMin.push(newNum);
		} else {
			int minValue = getMin();
			if(newNum<=minValue) {
				stackMin.push(newNum);
			}else {
				stackMin.push(minValue);
			}
		}
		stackData.push(newNum);
	}

	public int pop() {
		if(stackMin.isEmpty()) {
			// do nothing
		}else {
			stackMin.pop();
		}
		if(stackData.isEmpty()) {
			return -1;
		}else {
			return stackData.pop();
		}
		
	}
	private int getMin() {
		if (stackMin.isEmpty()) {
			System.out.println("stack is empty");
			return -1;
		}
		return stackMin.peek();
	}
	public static void main(String[] args) {
        GetMinStack_1 stack = new GetMinStack_1();
        int[] testNum = {4,2,4,6,5,0,1,10};
        for(int i:testNum){
            stack.push(i);
        }
        for(int i = 0; i < testNum.length; i++){
            System.out.println(stack.getMin()+" "+stack.pop());
        }
	}
}

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/81982557