代码随想录——每日温度(Leetcode 739)回顾

题目链接
在这里插入图片描述

for + while超时

单调栈

通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了。时间复杂度为O(n)。


单调栈的本质是空间换时间,因为在遍历的过程中需要用一个栈来记录右边第一个比当前元素高的元素,优点是整个数组只需要遍历一次。


单调栈里只需要存放元素的下标i就可以了,如果需要使用对应的元素,直接T[i]就可以获取。

class Solution {
    
    
    public int[] dailyTemperatures(int[] temperatures) {
    
    
        int[] res = new int[temperatures.length];
        Deque<Integer> stack = new LinkedList<>();
        for(int i = 0; i < temperatures.length; i++){
    
    
            while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
    
    
                res[stack.peek()] = i - stack.peek();
                stack.pop();
            }
            stack.push(i);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_46574748/article/details/141801178