Daily Temperatures_Week15

Daily Temperatures_Week15

题目:(Daily Temperatures) ←链接戳这里

题目说明:
Given a list of daily temperatures, produce a list 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 temperatures = [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].

难度: Medium

解题思路:
题意为:给出一系列天数的温度,要求返回一个数组,表示对每一天,还有几天能遇到更温暖的日子,如果后面没有更暖的日子则返回0
这道题最简单的思路就是对每一天,都往后遍历数组,直到找到更暖的一天/到达数组尾端=没有找到更暖的一天。而经过别人的的启发,了解到别的一些方式来解。
因为温度从30~100度,那对于每个温度,比如73,我通过遍历数组来找到74或者其他高于73的温度的天数,记在一个数组里,这样就可以比较快地找到更难的一天

代码如下:

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temps) {
        int n = temps.size();
        vector<int> daysToWait(n, 0);//数组记录答案:还有多少天变暖

        //temperatureOnNext记录后续天里,每个温度在第几天,若不存在该温度的天,则设置为int的最大值
        vector<int> temperatureOnNext(101, INT_MAX);
        for (int i = n - 1; i >= 0; i--) {
            //earliest用于记录最早遇到更暖的一天的在数组里的位置
            int earliest = INT_MAX;
            for (int t = temps[i] + 1; t <= 100; t++) {
                earliest = min(earliest, temperatureOnNext[t]);
            }
            if (earliest != INT_MAX) {
                //检测到有更暖的一天,记录到daysToWait中
                daysToWait[i] = earliest - i;
            }
            //记录当前温度最后的日子为第i天
            temperatureOnNext[temps[i]] = i;
        }
        return daysToWait;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38072045/article/details/78819352