【重点】【单调栈】739.每日温度

题目

法1:单调栈

必须掌握算法,关于单调栈、单调队列和环形队列相关参见《算法小抄》相关内容。
类似题目:下一个更大的元素

Python

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        n = len(temperatures)
        res = [0] * n
        stack = collections.deque()
        for i in range(n-1, -1, -1):
            cur = temperatures[i]
            while len(stack) > 0 and temperatures[stack[-1]] <= cur:
                stack.pop()
            res[i] = 0 if len(stack) == 0 else stack[-1] - i
            stack.append(i)

        return res

Java

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n = temperatures.length;
        int[] res = new int[n];
        Stack<Integer> s = new Stack<>();
        for (int i = n - 1; i >= 0; --i) {
            while (!s.isEmpty() && temperatures[s.peek()] <= temperatures[i]) {
                s.pop();
            }
            res[i] = s.isEmpty() ? 0 : s.peek() - i;
            s.push(i);
        }

        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值