当前位置:网站首页>Stack: daily temperature

Stack: daily temperature

2022-06-13 02:45:00 Zeng Qiang

subject

https://leetcode-cn.com/problems/iIQa4I/

Their thinking

Save the subscript of daily temperature in the array with a stack , And maintain a monotonically decreasing stack .

step :

  1. Push : Traverse daily temperature , If the stack is empty , Save the current temperature to the stack .( Save subscript ).
  2. Out of the stack : Compare the top element with the current temperature , If the stack top element is less than the current temperature , Out of the stack , Complete the statistics of the last heating days . Continue to stack to determine whether there are days less than the current temperature , Finally, subscript the array of current temperature onto the stack .
  3. state : As long as the current temperature is greater than the elements in the stack , We'll be out of the stack , So we can find that the stack is always decreasing .

Why choose a data structure : Stack .
Because we need to compare the current temperature with the previous temperature , So this is a derivation process from back to front , Consider choosing a stack as a data set .

Code

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

summary

Subscript the daily temperature in the array with a stack , Maintain a monotonic decreasing stack .

原网站

版权声明
本文为[Zeng Qiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280538227264.html