单调栈--1

核心方法http://t.csdn.cn/VYgb1

首先我们需要理解栈中的三个核心方法:pushpoppeek

push:往栈顶添加元素

pop:从栈顶移除元素

peek:获取栈顶元素,并不做任何添加删除操作

739.每日温度

https://leetcode.cn/problems/daily-temperatures/submissions/

 如果当前遍历的元素 大于栈顶元素,表示栈顶元素的右边的最大的元素就是当前遍历的元素,
        	所以弹出 栈顶元素,并记录 
        	如果栈不空的话,还要考虑新的栈顶与当前元素的大小关系 
        否则的话,可以直接入栈。
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int len = temperatures.length;
        int[] res = new int[len];

        Deque<Integer> stack = new LinkedList<>();
        stack.push(0);
        for(int i =1;i<len;i++){
           if(temperatures[i] <= temperatures[stack.peek()]){
               stack.push(i);
           }else {
               while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){
                res[stack.peek()] = i - stack.peek();
                stack.pop();
           }
           stack.push(i);
        } 
     }
            return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_56194193/article/details/129028886