请根据每日 气温 列表 temperatures ,请计算在每一天需要等几天才会有更高的温度。如果气温在这之后都不会升高,请在该位置用 0 来代替。
分析:本题用一个栈来记录目前遍历的没有比栈中元素高的温度,这种栈即为单调栈,即只有比当前元素低(不符合题意)的元素可以入栈,而只要当前元素比栈中 元素高,那么就依次将栈中元素弹出,并记录结果,最后再讲当前元素入栈。
参考代码:
public int[] dailyTemperatures(int[] temperatures) {
int[] ret = new int[temperatures.length];
Stack
stack.push(0);
int index=1;
while(index
stack.push(index);
}else{
while(!stack.isEmpty()&&temperatures[index]>temperatures[stack.peek()]){
int n=stack.pop();
ret[n]=index-n;
}
stack.push(index);
}
index++;
}
return ret;
}
