zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    提升键盘可访问性和AT可访问性
    2个小技巧
    设计模式(6): 数据抽象与业务封装
    目录
    医疗经济学
    医疗场景下的行为经济学(三)
    抗体、免疫
    医疗场景下的行为经济学(二)
    医疗场景下的行为经济学(一)
    单身社会如何生活-日本纪录片ガイアの夜明け系列
  • 原文地址:https://www.cnblogs.com/immjc/p/8401467.html
Copyright © 2011-2022 走看看