69.Daily Temperatures(日常气温)
Level:
Medium
题目描述:
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].
思路分析:
设置一个栈,栈中保存的元素为对应天数和它当日的气温,遍历气温数组,当栈为空时,将第一天的天数,即下标和其对应的气温压入栈中,然后判断后来的元素的气温是否大于栈顶元素的气温,如果大于,那么弹出栈顶元素得到弹出元素和当前元素的相差天数,保存为弹出元素的结果,负责将当前元素压入栈,继续向下进行遍历。
代码:
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;
    }
}
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号