题目描述
给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。
示例
输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]
Code
public class Code {
public static void main(String[] args) {
Code code = new Code();
int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
System.out.println(Arrays.toString(code.dailyTemperatures(temperatures)));
}
/**
* 计算一个更高的温度列表
*/
public int[] dailyTemperatures(int[] T) {
//入参校验
int length = T.length;
int[] result = new int[length];
//i代表的是哪天具体的温度
for (int i = length - 2; i >= 0; i--) {
//j代表i后面的温度,result[j]代表的是比j大的数在第几个位置,所以这里不需要j++,直接+ result[j] 即可
for (int j = i + 1; j < length; j += result[j]) {
if (T[i] < T[j]) {
result[i] = j - i;
break;
}
//如果result[j]为0,说明后续没有更高的温度了,直接返回即可
if (result[j] == 0) {
result[i] = 0;
break;
}
}
}
return result;
}
}
题目来源: 739. 每日温度