week 1: 实现一个特殊的栈,在实现栈的基本功能的基础上,在实现返回栈中最小的元素的操作。

topic requirement:
1.pop,push,getmin,操作的时间复杂度都是0( 1 );
2.设计栈的类型可以使用现成的栈的结构。

 

thoughts:考虑时间复杂度是O(1),用两个栈来实现此特殊栈。

the first method:

             两个栈同时压入,同时弹出

the second method:

              当前数<=min栈,压入min栈  ;当前数=min栈栈顶,data栈和min栈同时弹出

the code first approach:

public class GetMinStack1 {
	public static class SelfStack1{
		private Stack<Integer> stackData;
		private Stack<Integer> stackMin;
		
		public SelfStack1() {
			this.stackData = new Stack<Integer>();
			this.stackMin = new Stack<Integer>();
		}
		
		public void push(int newNum) {
			if(this.stackMin.isEmpty()) {
				this.stackMin.push(newNum);
			}else if(newNum<this.getmin()) {
				this.stackMin.push(newNum);
			}
			this.stackData.push(newNum);
		}
		
		public int getmin() {
			if(this.stackMin.isEmpty())
				throw new RuntimeException("Your stack is empty");
			return this.stackMin.peek();
		}
		
		public int pop() {
			if(this.stackData.isEmpty())
				throw new RuntimeException("Your stack is empty");
			this.stackMin.pop();
			return this.stackData.pop();
		}
		
	}
	
	public static void main(String[] args) {

		
		SelfStack1 stack1 = new SelfStack1();
		stack1.push(23);
		System.out.println(stack1.getmin()); //23
		stack1.push(2);
		System.out.println(stack1.getmin());//2
		stack1.push(3);      
		System.out.println(stack1.getmin());  //2
		System.out.println(stack1.pop());    //3
		System.out.println(stack1.getmin());  //2
	}

}

the code second approach:

public class GetMinStack2 {
	public static class  SelfStack2{
		private Stack<Integer> stackData;
		private Stack<Integer> stackMin;
		
		public SelfStack2() {
			this.stackData = new Stack<Integer>();
			this.stackMin = new Stack<Integer>();
		}
		
		public void push(int newNum) {
			if(this.stackMin.isEmpty()) {
				this.stackMin.push(newNum);
			} else if(newNum <= this.getmin()) {
				this.stackMin.push(newNum);
			}
			this.stackData.push(newNum);
			
		}
	    
	    public int getmin() {
	    	if(this.stackMin.isEmpty()) {
	    		throw new RuntimeException("Your stack is empty");
	    	}
	    	return this.stackMin.peek();	
     	}
	    
	    public int pop() {
	    	if(this.stackData.isEmpty())
	    		throw new RuntimeException("Your stack is empty");
	    	int value = this.stackData.pop();
	    	if(value == this.getmin())
	    		this.stackMin.pop();
	    	return value;
	    }
}
	
	public static void main(String[] args) {

		
		SelfStack2 stack1 = new SelfStack2();
		stack1.push(23);
		System.out.println(stack1.getmin()); //23
		stack1.push(2);
		System.out.println(stack1.getmin());//2
		stack1.push(3);      
		System.out.println(stack1.getmin());  //2
		System.out.println(stack1.pop());    //3
		System.out.println(stack1.getmin());  //2
	}

}

 reference:左神   

encouragement:  

             不积跬步,无以至千里

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页