根据每⽇⽓温列表,请重新⽣成⼀个列表,对应位置的输⼊是你需要再等待多久温度才会升⾼超过该⽇的天数。如果之后都不会升⾼,请在该位置0来代替
例如,给定⼀个列表temperatures = [73, 74, 75, 71, 69, 72, 76, 73],
你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]
方式一:
暴力
public void fun1(){int[] temperatures= new int[]{73, 74, 75, 71, 69, 72, 76, 73};// 2 1 1 0 0int[] temp=new int[temperatures.length];for(int x=0;x<temperatures.length;x++){for(int i=x+1;i<temperatures.length;i++){if(temperatures[i]>temperatures[x]){temp[x]=i-x;break;}else {temp[x]=0;}}}for(int x=0;x<temp.length;x++){System.out.println("x="+temp[x]);}}
方式二:
数组
public void fun2(){
int[] temperatures= new int[]{73, 74, 75, 71, 69, 72, 76, 73};
int[] temp=new int[temperatures.length];
for(int x=0;x<temp.length;x++){
temp[x]=0;
}
// int[] temperatures= new int[]{73, 74, 75, 71, 69, 72, 76, 73};
// 1 1 4 2 1 1 0 0
for(int x=temperatures.length-1;x>=0;x--){
for(int i=x+1;i>=0 && i<=temperatures.length-1;i++){
if(temperatures[i]>temperatures[x]){
temp[x]=i-x;
break;
}
}
}
for(int x=0;x<temp.length;x++){
System.out.println("x="+temp[x]);
}
}
方式三:
栈
public void fun3(){
int[] temperatures= new int[]{73, 74, 75, 73, 69, 72, 76, 73};
int[] temp=new int[temperatures.length];
Stack<Value> stack=new Stack<>();
// int[] temperatures= new int[]{73, 74, 75, 71, 69, 72, 76, 73};
// 1 1 4 2 1 1 0 0
// int[] temperatures= new int[]{73, 74, 75, 73, 69, 72, 76, 73};
// 1 1 4 3 1 1 0 0
for(int x=0;x< temperatures.length-1;x++){
if(stack.empty()){
stack.push(new Value(x,temperatures[x]));
}else {
while (!stack.empty()){
Value peek = stack.peek();
if(temperatures[x]> peek.data){
stack.pop();
temp[peek.index]=x-peek.index;
}else {
stack.push(new Value(x,temperatures[x]));
break;
}
}
stack.push(new Value(x,temperatures[x]));
}
}
for(int x=0;x<temp.length;x++){
System.out.println("x="+temp[x]);
}
}
public static class Value{
int index;
int data;
public Value(int index, int data) {
this.index = index;
this.data = data;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
