• leetcode算法题目-每日气温


    一、题目

    根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。

    例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

    提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

    二、解题思路

    其实我发现了,leetcode的题目读起来确实有点儿费劲,不过读懂了就不太难了,这道题的意思就是,从温度数组的左边向右边看,遍历数组中的每一个数,找到比当前温度大的数,下标相减、相减的结果替换掉此数组中该数,如果没有就默认为0,替换完毕后,继续查看下一个温度,和数组后面的温度进行对比,直到全部替换。

    三、代码如下:

    /**
     * 
     * @version: 1.1.0
     * @Description: 气温列表
     * @author: wsq
     * @date: 2020年6月11日上午11:20:10
     */
    public class SecondProblem {
        public static void main(String[] args) {
            int[] temperatures = new int[] { 73, 74, 75, 71, 69, 72, 76, 73 };
            int[] resultArray = getDayArray(temperatures);
            System.out.println(Arrays.toString(resultArray));
        }
    
        public static int[] getDayArray(int[] array) {
            // 遍历温度,进行对比,并添加到对应的数组
            for (int i = 0; i < array.length - 1; i++) {
                for (int j = i + 1; j < array.length; j++) {
                    // 判断比自己温度高的相差几天
                    if (array[i] < array[j]) {
                        array[i] = j - i;
                        break;
                    }
                    if (j == array.length - 1) {
                        array[i] = 0;
                    }
                }
            }
            // 最后一位为固定值
            array[array.length - 1] = 0;
            return array;
        }
    }
  • 相关阅读:
    字节和字符,对信息进行编码
    关于TCP的可靠性
    TCP和流
    Socket:流,TCP连接,TCP可靠性概述
    C#中的泛型 Part1
    C# 泛型理解0
    2010 Stanford Local ACM Programming ContestH解题报告
    母函数模板
    poj 1385Lifting the Stone解题报告
    poj 1015Jury Compromise解题报告
  • 原文地址:https://www.cnblogs.com/mcjhcnblogs/p/13092831.html
Copyright © 2020-2023  润新知