69.Daily Temperatures (daily temperature)

Level:

  Medium

Subject description:

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

Analysis of ideas:

  Setting a stack, stored in the stack elements corresponding to the number of days and its temperature day, traversing the temperature array, when the stack is empty, the number of days of the first day, i.e., subscripts and the corresponding temperature onto the stack, and then determines later, if the temperature of the element is greater than the temperature of the top element, If so, then pop the top element to get the number of days difference between the pop-up element and the current element, saved as a result of pop-up element, is responsible for the current element onto the stack, proceed down traversal.

Code:

public class Solution{
    public int []dailyTemperatures(int []T){
        Stack<int []>s=new Stack<>();//存放下标和其对应的温度
        int []res=new int [T.length];
            for(int i=0;i<T.length;i++){
                while(!s.isEmpty()&&s.peek()[1]<T[i]){
                    int []temp=s.pop();
                    res[temp[0]]=i-temp[0];//相差的天数
                }
                s.push(new int[]{i,T[i]});
            }
        return res;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11097903.html