• [LeetCode] 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].

    给定一个温度表,找出需要对于每一个温度,多少天后的温度比当前温度高。将结果放入一个数组中。

    思路1:遍历2次温度表,找出符合条件的天数。

    复杂度为O(n^2) 超时

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& temperatures) {
            vector<int> res(temperatures.size(), 0);
            for (int i = 0; i < temperatures.size(); i++) {
                for (int j = i + 1; j < temperatures.size(); j++) {
                    if (temperatures[j] - temperatures[i] > 0) {
                        res[i] = j - i;
                        break;
                    }
                }
            }
            return res;
        }
    };
    // TLE
    TLE

    思路2:使用一个stack来存储待比较的元素,直到遇到符合条件的值后再一一出栈比较。只需要遍历一次温度表。

    class Solution {
    public:
        vector<int> dailyTemperatures(vector<int>& temperatures) {
            vector<int> res(temperatures.size(), 0);
            stack<pair<int, int>> stk;
            for (int i = 0; i < temperatures.size(); i++) {
                while (!stk.empty() && temperatures[i] > stk.top().first) {
                    res[stk.top().second] = i - stk.top().second;
                    stk.pop();
                }
                stk.push(make_pair(temperatures[i], i));
            }
            return res;
        }
    };
    // 233 ms
  • 相关阅读:
    老友记实战,17上
    老友记实战,9下
    老友记实战,5下
    公共样式base.css
    单选框radio总结(获取值、设置默认选中值、样式)
    js tab切换
    HTTP状态码100、200、300、400、500、600的含义
    微信小程序事件绑定
    微信小程序获取手机验证码
    js滚动到指定位置导航栏固定顶部
  • 原文地址:https://www.cnblogs.com/immjc/p/8401467.html
Copyright © 2020-2023  润新知