zoukankan      html  css  js  c++  java
  • 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;
        }
    }
    
  • 相关阅读:
    Linux日常之命令sort
    Linux日常之命令sed
    Linux日常之命令grep
    Linux日常之命令awk
    Linux日常之命令tee
    Linux日常之数据重定向
    Hibernate打印SQL及附加参数
    使用D3 Geo模块画澳大利亚地图
    基于Spring-WS的Restful API的集成测试
    做项目时需要考虑的安全性问题
  • 原文地址:https://www.cnblogs.com/yjxyy/p/11097903.html
Copyright © 2011-2022 走看看