1. 图解
2. 代码
```java
package leetCode.temperatures;
import java.util.Stack;
/**
* 根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
*
* 例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
*
* 提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/daily-temperatures
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
/** 最近关系类的题目第一时间就应该想到用栈 */
public class Temperature01 {
//我的:229ms
public static int[] dailyTemperatures1(int[] arr) {
int[] result = new int[arr.length];
int count = 0;
//左至右遍历
for (int i = 0; i < arr.length-1; i++) {
//如果相邻右边的数大,直接放 1
if (arr[i] < arr[i+1]) {
result[i] = 1;
count = 0; //置0
continue;
} else {
//否则遍历 i 右边的数,直到找出碰到更大的数
for (int j = i+1; j < arr.length; j++) {
if (arr[j] > arr[i]) {
count = j - i;
break;
}
}
}
result[i] = count;
}
return result;
}
//大佬的:54ms
//找出数组中大于当前元素的第一个元素,到当前元素的距离
//递减栈,当前元素与栈中元素比较,小则入栈,大则出栈并将二者之间的下标差值为出栈元素的结果值,并继续比较下一个栈顶元素
//如果栈为空,直接入栈(表示前面元素都找到了比自己大的值)
public static int[] dailyTemperatures2(int[] T) {
Stack<Integer> stack = new Stack<>();
int[] res = new int[T.length];
for(int i = 0; i < T.length; i++) {
//T[i] > T[stack.peek()] :当前数比栈顶下标所对应数大
//栈顶下标是离 i 最近的下标
while(! stack.isEmpty() && T[i] > T[stack.peek()]) {
int temp = stack.pop();
res[temp] = i - temp; //
}
stack.push(i); //一定执行,把 i 入栈
}
return res;
}
public static void main(String[] args) {
int[] arr = new int[]{73,74,75,71,69,72,76,73};
int[] ints = dailyTemperatures2(arr);
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[i] + " ");
}
}
}
来源:CSDN
作者:西瓜和柚子你喜欢哪个
链接:https://blog.csdn.net/jswrcsdn1/article/details/103647458