LeetCode 第739题:每日温度

2021-05-08  本文已影响0人  放开那个BUG

1、前言

题目描述

2、思路

使用单调栈的思路,从左往右依次遍历,只不过 stack 记录的不是数字,而是数组索引,因为得到的结果保存的是两个数字之间的距离,直接用 stack 中的索引与当前数字的索引相减即可。

3、代码

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] res = new int[T.length];
        Stack<Integer> stack = new Stack<>();
        for (int i = T.length - 1; i >= 0; i--) {
            while(!stack.isEmpty() && T[i] >= T[stack.peek()]){
                stack.pop();
            }
            res[i] = stack.isEmpty() ? 0 : stack.peek() - i;
            stack.push(i);
        }
        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读