【题目描述】

给定一个整数数组 ​temperatures​ ,表示每天的温度,返回一个数组 ​answer​ ,其中 ​answer[i]​ ​i​ 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 ​0​ 来代替。

​​https://leetcode.cn/problems/daily-temperatures/?favorite=2cktkvj

【示例】

   【LeeCode】739. 每日温度_数组

【代码】admin

通过率 47 / 48  代码超时了  

思路:我们只需要知道最近一个大于temperatures[i]的值, 计算j - i的下表即可

package com.company;
import javax.swing.plaf.IconUIResource;
import java.util.*;

// 2022-02-13
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int[] res = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++){
for (int j = i + 1; j < temperatures.length; j++){
if (temperatures[j] > temperatures[i]){
res[i] = j - i;
break;
}
}
}
// System.out.println(Arrays.toString(res));
return res;
}
}

public class Test {
public static void main(String[] args) {
new Solution().dailyTemperatures(new int[] {89,62,70,58,47,47,46,76,100,70}); // 输出: [8,1,5,4,3,2,1,1,0,0]
new Solution().dailyTemperatures(new int[] {73,74,75,71,69,72,76,73}); // 输出: [1,1,4,2,1,1,0,0]
new Solution().dailyTemperatures(new int[] {30,40,50,60}); // 输出: [1,1,1,0]
new Solution().dailyTemperatures(new int[] {30,60,90}); // 输出: [1,1,0]
}
}

【代码】​​官方​

单调栈的思路   ​​动画视频(点击查看)​

   【LeeCode】739. 每日温度_数组_02

package com.company;
import javax.swing.plaf.IconUIResource;
import java.util.*;

// 2022-02-13
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
/**
* 入站元素要和当前栈内栈首元素进行比较
* 若大于栈首则 则与元素下标做差
* 若大于等于则放入
*/
Stack<Integer> stack = new Stack<>();
int[] res = new int[temperatures.length];
for (int i = 0; i < temperatures.length; i++){
while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
int preIndex = stack.pop();
res[preIndex] = i - preIndex;
}
// 注意 放入的是元素位置
stack.push(i);
}
System.out.println(Arrays.toString(res));
return res;
}
}

public class Test {
public static void main(String[] args) {
new Solution().dailyTemperatures(new int[] {89,62,70,58,47,47,46,76,100,70}); // 输出: [8,1,5,4,3,2,1,1,0,0]
new Solution().dailyTemperatures(new int[] {73,74,75,71,69,72,76,73}); // 输出: [1,1,4,2,1,1,0,0]
new Solution().dailyTemperatures(new int[] {30,40,50,60}); // 输出: [1,1,1,0]
new Solution().dailyTemperatures(new int[] {30,60,90}); // 输出: [1,1,0]
}
}