Monotonic stack -- 1

Core method http://t.csdn.cn/VYgb1

First of all, we need to understand the three core methods in the stack: pushpoppeek

push: add an element to the top of the stack

pop: remove an element from the top of the stack

peek: Get the top element of the stack without doing any addition or deletion operations

739. Daily temperature

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;
    }
}

Guess you like

Origin blog.csdn.net/weixin_56194193/article/details/129028886