【leetcode】单调栈 - 739. 每日温度(中等)

目录

  • 题目
  • 思路一 - 暴力遍历
  • 思路二 - 单调栈

题目

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

示例 1:

输入: temperatures = [73,74,75,71,69,72,76,73]
输出: [1,1,4,2,1,1,0,0]

示例 2:

输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

输入: temperatures = [30,60,90]
输出: [1,1,0]

提示:

1 <= temperatures.length <= 105
30 <= temperatures[i] <= 100

思路一 - 暴力遍历

通过两次循环遍历即可得出结果

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n=temperatures.length;
        int [] h=new int [n];
        
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                if(temperatures[i]<temperatures[j]) {
                    h[i]=j-i;
                    break;
                }
            }
        }
        return h;

    }
}

思路二 - 单调栈

通过单调栈的方式进行存储
存储的数据是下标值 ,判断数组(下标值)是否大于以及栈是否为空即可
具体代码如下:

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n=temperatures.length;
        int [] h=new int [n];

        Deque<Integer> stack=new LinkedList<>();

        for(int i=0;i<n;i++){
          while(!stack.isEmpty()&&temperatures[ stack.peek()]<temperatures[i]){
              int j=stack.pop();
              h[j]=i-j;  
          }
          stack.push(i);
        }
        return h;

    }
}

你可能感兴趣的:(算法,leetcode,算法)