码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Daily Temperatures

时间:2018-02-01 23:14:16      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:tco   比较   not   oss   blog   post   etc   col   pre   

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

 

[LeetCode] Daily Temperatures

标签:tco   比较   not   oss   blog   post   etc   col   pre   

原文地址:https://www.cnblogs.com/immjc/p/8401467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!