LeetCode-739

100 阅读1分钟

739. 每日温度 思路:维护一个单调栈
方法:新建一个数组存放等待的天数。维护一个递减的单调栈,存放温度递减的第X天,当新的元素T[i]比栈顶元素表示的当天温度高时,弹出栈顶元素,并用下标相减得出相差的天数,存入数组中。

/*执行用时:19 ms, 在所有 Java 提交中击败了67.15%的用户
内存消耗:46.6 MB, 在所有 Java 提交中击败了55.08%的用户*/
class Solution {
    public int[] dailyTemperatures(int[] T) {
        int len = T.length;
        int[] a = new int[len];
        Stack<Integer> s = new Stack<>();
        int num = Integer.MAX_VALUE;
        for(int i =0; i < len ; i++){
            while(!s.isEmpty() && T[i] > T[s.peek()]){
                int t = s.pop();
                a[t] = i - t;
            }
            s.push(i);
        }
        return a;
    }   
}