LeetCode 739.每日温度

132 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

题目:给定一个整数数组temperatures表示每天的温度,要求返回一个数组answer,其中answer[i]表示在i天后才会有更高的温度,如果都没有则用0代替。

解题思路

一开始想到的又是暴力解法,对于每一天的温度,我们可以直接查看其后面所有天的温度,用大于当天温度的索引减去当天索引即为更高温度的天数,可得代码如下:

public int[] dailyTemperatures(int[] temperatures){
        int len = temperatures.length;
        int[] result = new int[len];
        for(int i=0;i<len;i++){
            int index = i;
            while (index<len){
                if(temperatures[index]>temperatures[i]){
                    result[i] = index-i;
                    break;
                }
                index++;
            }
            if(index==len) result[i] = 0;
        }
        return result;
    }

上述代码的时间复杂度为O(n2)O(n^2),空间复杂度为O(n)O(n)

思路进阶(单调递减栈)

单调递减栈的思路很巧妙,其核心是保持栈中元素所对应的值为递减的,这里以一个实例来介绍单调递减栈的过程,假设数组为[73, 74, 75, 71, 69, 72, 76, 73]

  1. i=0时,初始时栈为空,则73对应的索引0入栈。
  2. i=1时,发现74>73,则栈顶元素0出栈,并且赋值res[stack.peek()] = i-stack.pop()。将1入栈。
  3. i=2时,发现75>74,则栈顶元素1出栈,并且赋值res[stack.peek()] = i-stack.pop()。将2入栈。
  4. i=3时,发现71<75,将3入栈。
  5. i=4时,发现69<71,将4入栈。
  6. i=5时,此时栈为[2, 3, 4],因为此时72>69,因此将4出栈,并且赋值res[stack.peek()] = i-stack.pop(),之后71<72,将3出栈,同样赋值,而72<75,因此5入栈。
  7. i=6时,76大于72,因此将5出栈,同上面赋值,76>752也出栈赋值,之后6入栈。
  8. i=7时,73<76,直接入栈。
  9. 至此得到最终结果。

从上面过程可以发现,入栈的索引是待赋值的索引,索引出栈也即赋值时机,可得代码如下:

public static int[] dailyTemperatures2(int[] temperatures){
    Stack<Integer> stack = new Stack<>();
    int len = temperatures.length;
    int[] result = new int[len];
    for(int i=0;i<len;i++){
        while(!stack.isEmpty()&&temperatures[i]>temperatures[stack.peek()]){
            int peek = stack.pop();
            result[peek] = i - peek;
        }
        stack.push(i);
    }
    return result;
}

时间复杂度和空间复杂度都是O(n)O(n)