The monotonic stack calculates the adjacent maximum value of the daily temperature array

Insert picture description here

class Solution {
    
    
    public int[] dailyTemperatures(int[] T) {
    
    
        LinkedList<Integer> stack=new LinkedList<>();
        int length=T.length;
        int[] ans=new int[length];
        for(int i=0;i<length;i++){
    
    

            if(!stack.isEmpty()){
    
    
                   while(!stack.isEmpty()&&T[i]>T[stack.peek()]){
    
    
                    ans[stack.peek()]=i-stack.peek();
                    stack.pop();
                    }
                    stack.push(i);
            }else {
    
    
                stack.push(i);
            }
        }

        while(!stack.isEmpty()){
    
    
            ans[stack.pop()]=0;
        }

        return ans;




    }
}

Guess you like

Origin blog.csdn.net/changbaishannefu/article/details/115219864