LeetCode|739. Daily Temperatures

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].

Solution

这个题的题意很容易理解,就是按索引顺序找出每个元素比它自身大的元素离当前元素的距离。

解法一

老规矩,先给出一个最简单的解法。这个解法就是遍历数组,针对每个元素从该元素的索引位置开始遍历到数组末尾,直到遇到比自身大的元素的时候返回遍历的次数temp。可以说是很符合直觉的解法,性能当然也是意料之中的糟糕。

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] result=new int[T.length];
        for(int i=0;i<T.length;i++){
            int temp=0;
            for(int j=i+1;j<T.length;j++){
                  temp++;
                if(T[j]>T[i]){
                    break;
                }
                if(j==T.length-1){
                    temp=0;
                }
            }
            result[i]=temp;
        }
        return result;
    }
}

该解法性能如下:

执行用时 : 653 ms, 在所有 Java 提交中击败了5.00%的用户
内存消耗 :42.8 MB, 在所有 Java 提交中击败了93.00%的用户

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,160评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 14,269评论 3 20
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,150评论 0 13
  • 看牙真贵! 2018年,快到年底了,终于有勇气买进了牙科诊所。 2008年,第一次进牙科诊所的经历,还记忆犹新。 ...
    辛小婷阅读 4,320评论 3 1
  • jquery用法思想 同一个函数完成取值和赋值 操作行间样式 特别注意 选择器获取的多个元素,获取信息获取的是第一...
    Devops海洋的渔夫阅读 1,319评论 0 1