739. 每日温度

2022-01-05  本文已影响0人  名字是乱打的

一 题目:

二 思路:

单调栈
这里注意,如果气温在这之后都不会升高,则将该位置用0来代替。

三 代码:

单调栈法

class Solution {
    /**
     * 单调栈法
     * @param temperatures
     * @return
     */
    public int[] dailyTemperatures(int[] temperatures) {
        //存储没找到更高温度的下标
        Stack<Integer> stack=new Stack<>();
        //结果集
        int[] res=new int[temperatures.length];

        for (int i = 0; i < temperatures.length; i++) {
            while (!stack.isEmpty()&&temperatures[stack.peek()]<temperatures[I]){
                Integer index = stack.pop();
                res[index]=i-index;
            }
            stack.push(i);
        }

        return res;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读