LeetCode 739. 每日温度

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37143673/article/details/102463383

LeetCode 739. 每日温度

题目

在这里插入图片描述

我的思路

循环数组
循环数组的同时,循环栈
判断栈顶索引所对应的数组中的值,与循环到的值温度哪个高
由于栈后进先出的特性,是一天一天往前推的
如果循环到的这个值高,说明升温了,以此计算索引差值,计算多少天升温
移除栈顶元素,同时更新栈顶这个索引在数组中的值,也就是几天升温

代码

class Solution {
    public int[] dailyTemperatures(int[] T) {
        // 定义一个栈,后进先出
        Stack<Integer> stack = new Stack<>();
        // 要输出的数组
        int[] res = new int[T.length];
        // 循环把索引入栈
        for (int i = 0; i < T.length; i++) {
            // 如果栈里有值,且栈顶元素所对应的值小于该值
            // 说明升温了则移除这个栈顶值,且把相减获取中间差了多少天
            while (!stack.isEmpty() && T[stack.peek()] < T[i]) {
                int t = stack.pop();
                res[t] = i - t;
            }
            // 索引入栈
            stack.push(i);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37143673/article/details/102463383