java_basic_MinStack_O(1)时间复杂度

【练习】:实现一个特殊的栈,实现栈的基本功能,再实现返回栈中的最小值

【要求】:pop.push,getMin 操作时间复杂度为O(1)

【过程】:

  1. 初始化2个栈,一个叫stackData,一个叫stakMin,

push过程:

  1. stackData栈中,每次都装入新的num
  2. stackMin栈中,第一次数字与就是num,后面每次来了新的num数字,比较当前数与stackMin栈顶的数,stackMin栈中装入更小的数字

pop过程:

  1. 每次stackData弹出一个数,stackMin也同样弹出一个数,

这样就实现了,每次读取stackMin中的栈顶,就是当前stackdata栈中的最小值,时间复杂度为O(1)

【代码】:


// 实现一个特殊的栈,实现栈的基本功能,再实现返回栈中的最小值 【要求:pop.push,getMin 操作时间复杂度为O(1)】

import java.util.Stack;



public class ArrayStack_03 {
	public  Stack<Integer> stackData;
	public Stack<Integer> stackMin;
	// 构造方法-初始化2个栈结构 data , min
	public ArrayStack_03() {
		this.stackData = new Stack<Integer>();//定义2个栈,用系统提供的栈结构
		this.stackMin = new Stack<Integer>();
	}
	//  --> push操作 同时获得最小值O(1)
	// 如果stackMin栈中为空,新的数直接加入,
	// 如果stackMin栈中不为空,新的数 > 栈顶数 , stackMin中放入更小的数, 栈顶
	// 如果stackMin栈中不为空,新的数 < 栈顶数 , stackMin中放入新的数(更小的数)
	// 同时,stackData栈中每次都要放入新的数
	
	public void push(int newNum) {
		if (this.stackMin.isEmpty()) {
			this.stackMin.push(newNum); // 栈结构自带的push功能
		}else if (newNum < this.stackMin.peek()) {
			this.stackMin.push(newNum);
		}else {
			newNum = this.stackMin.peek();
			this.stackMin.push(newNum);
		}
		this.stackData.push(newNum);
	}
	
	// --> 弹出pop ,每次stackData栈弹出,stackMin栈也弹出一个数
	public int pop() {
		if (this.stackData.isEmpty()) {
			throw new RuntimeException("Your stack is empty");
		}
		this.stackMin.pop();
		return this.stackData.pop();
	}
	
	// 每次的最小值都是stackMin栈的栈顶元素
	public int getMin() {
		if (this.stackData.isEmpty()) {
			throw new RuntimeException("Your stack is empty");
		}
		return this.stackMin.peek();
	}
	
	
	public static void main(String[] args) {
		int num = 5;
		ArrayStack_03 myStack = new ArrayStack_03();
//		for (int i=0; i < num; i++) {
//			myStack.push(i);
//		}
		myStack.push(12);
		myStack.push(13);
		myStack.push(14);
		myStack.push(11);
		
		System.out.println(myStack.getMin());
		System.out.println("====================");
		
		System.out.println(myStack.pop());
		System.out.println(myStack.pop());
		System.out.println(myStack.pop());
		System.out.println(myStack.pop());
		
//		for (int j = 0; j< num; j++) {
//			System.out.println(myStack.pop());
//		}
//		
	}
	
	

}

【代码结果】:

11
====================
11
12
12
12

猜你喜欢

转载自blog.csdn.net/sinat_15355869/article/details/81810548