补第十四周Leetcode算法博客

补第十四周Leetcode算法博客

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

题目的描述很简单,找出所有天数之后最邻近的温度更高的天数
一开始想了一个算法

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> warmlist;
        for (int i = 0; i < temperatures.size(); i++) {
            int iswarm = 1;
            int j;
            for (j = i + 1; j < temperatures.size(); j++) {
                if (temperatures[i] < temperatures[j]) {
                    warmlist.push_back(iswarm);
                    break;
                } else {
                    iswarm++;
                    if (j == temperatures.size() - 1) {
                        iswarm = 0;
                        warmlist.push_back(iswarm);
                    }
                }
            }
        }
        warmlist.push_back(0);
        return warmlist;
    }
};

image_1c2cd3g571lot1j1o14dc1m0mivk9.png-101.2kB
这个结果的样例是可以过的,但是在之后复杂的case里面会出现超时的问题,这个算法的主题是要求我们使用Stack栈结构实现O(n)时间复杂度的算法,因此我们要重构算法

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int length = temperatures.size();
        vector<int> warmlist(length, 0);
        stack<pair<int, int>> stk; //temperature, position
        for (int i = 0; i < temperatures.size() - 1; i++) {
            if (temperatures[i] < temperatures[i+1]) {
                warmlist[i] = 1;
                while (!stk.empty() && temperatures[i+1] > stk.top().first) {
                    warmlist[stk.top().second] = i + 1 - stk.top().second;
                    stk.pop();
                }
            } else {
                stk.push(make_pair(temperatures[i], i));
            }
        }
        return warmlist;
    }
};

这里的思路是,我们为了避免O(n^2)嵌套遍历两次vector,当我们找到下一天的温度不大于当天气温时,我们将当天的温度和日期存在一个栈结构中,因为在给定一天时,我们只关心里这天最近的之后的更温暖的日期,所以当我们找到一个更温暖的天气时,我们在从栈顶取出之前保存的气温来做比较

算法运行结果

image_1c2ce64m41fr1i5512cc1f4h64jm.png-114.4kB

这道题让我们意识到当算法正确但是有超时问题时,可以考虑用空间换时间。存储一些有效的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值