题目:
题目.png思路:
1:第一种思路,创建两个栈,一个栈实现栈的基本操作,另一个栈用于记录所加数值中最小的元素,如果加入的元素比辅助栈的栈顶小于或者等于,就入辅助栈,否则不加入,最后辅助栈的栈顶就是最小元素。弹出的时候,如果弹出的值辅助栈和基础栈的值一样,辅助栈就弹出否则只弹出基础栈。
2.第二种思路,也是创建辅助栈,不过这次辅助栈也随着基础栈加元素而加,加的规则是,如果加入的数值比辅助栈的栈顶小,就加入这个数,如果大于等于,就再加依次当前的栈顶。弹出的时候都一期弹出。
代码:
//方法一:
public static class MyStack1{
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack1(){
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int num){
if (this.stackMin.isEmpty()){
this.stackMin.push(num);
}
else if (num<=getMin()){
this.stackMin.push(num);
}
this.stackData.push(num);
}
public int pop(){
if (this.stackData.isEmpty()){
throw new RuntimeException("Your stack is empty");
}
int value = this.stackData.pop();
if (value==getMin()){
this.stackMin.pop();
}
return value;
}
public int getMin(){
if (this.stackMin.isEmpty()){
throw new RuntimeException("Your stack is empty");
}else {
return this.stackMin.peek();
}
}
}
//方法二
public static class MyStack2{
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public MyStack2(){
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int num){
if (this.stackMin.isEmpty()){
this.stackMin.push(num);
}
if (num<this.stackMin.peek()){
this.stackMin.push(num);
}else {
this.stackMin.push(this.stackMin.peek());
}
this.stackData.push(num);
}
public int pop(){
if (this.stackMin.isEmpty()){
throw new RuntimeException("your statck is empty");
}
this.stackMin.pop();
return this.stackData.pop();
}
public int getmin(){
if (this.stackMin.isEmpty()){
throw new RuntimeException("your statck is empty");
}
return this.stackMin.peek();
}
}
网友评论