思路:运用单调栈,当第一个元素进来时,只存他的i值,即数组中的位置值,方便以后判断。
第一个元素进来时会先经过if判断,如果栈是空的就直接push,然后continue让第二个进来,第二个就不会经过if判断直接进入while循环
注意进入while循环时,peek会有栈顶为空的异常风险,所以要加一个非空判断,如果是空则直接跳过while把元素push进去,这里要注意判断为空时不能用|| 应该用&&
在while循环里,如果当前i对应的温度比栈顶的元素对应的值大,则计算出来他们相差的天数,保存在result数组。因为栈里存的是i下标(天数值)所以计算起来方便,
result[stack.peek()]:是栈顶元素对应的下一次大于温度的天数
i-stack.pop(): 当前天数-栈顶对应天数
while循环结束,表示栈里已经没有比当前天数的温度值小,则将他push进栈,然后下一天进来,重新来过。
stack.peek() 是 Stack 类中的一个方法,用于返回栈顶元素而不移除它。与 stack.pop() 不同的是,peek() 只查看栈顶元素而不会将其从栈中弹出。如果栈为空,peek() 会返回 null 或抛出 EmptyStackException,具体取决于使用的栈实现。
import java.util.Stack;
public class EveryDayTemputure {
public static void main(String[] args) {
int[] temperatures = {73,74,75,71,69,72,76,73};
int[] ints = dailyTemperatures(temperatures);
for (int i : ints) {
System.out.println(i);
}
}
public static int[] dailyTemperatures(int[] temperatures) {
Stack<Integer> stack = new Stack<>();
int [] result = new int[temperatures.length];
for (int i = 0; i <temperatures.length ; i++) {
if(stack.isEmpty()){
stack.push(i);
continue;
}
while ( !stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
result[stack.peek()]= i-stack.pop();
}
stack.push(i);
}
return result;
}
}