LeetCode 739. Daily Temperatures

LeetCode 739. Daily Temperatures (每日温度)

题目

链接

https://leetcode-cn.com/problems/daily-temperatures/

问题描述

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

示例

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

提示

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

思路

单调栈思路,不过这里栈存放的应该是数组的序列,比较时用该位置的数比较。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(n)

代码

Java

    public int[] dailyTemperatures(int[] temperatures) {
        Stack<Integer> stack = new Stack<>();
        int[] ans = new int[temperatures.length];
        for (int i = temperatures.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && temperatures[stack.peek()] <= temperatures[i]) {
                stack.pop();
            }
            if (!stack.isEmpty()) {
                ans[i] = stack.peek() - i;
            } else {
                ans[i] = 0;
            }
            stack.push(i);
        }
        return ans;
    }
posted @ 2022-03-31 23:04  cheng102e  阅读(29)  评论(0编辑  收藏  举报