领扣(leetcode)

739. 每日温度

2018-10-05  本文已影响0人  莫小鹏

题目描述

根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高的天数。如果之后都不会升高,请输入 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的都是 [30, 100] 范围内的整数。

分析

使用堆栈保存还没遇到大于自己的数组元素的索引
遍历数组元素,跟栈顶元素比较,如果大于栈顶的元素,则保存栈顶元素的结果,并出栈。如果栈非空,继续跟栈顶的元素比较。

代码

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> res(n, 0);
        stack<int> s; //保存还没遇到大于自己的元素的索引
        for(int i = 0; i < n; i++) {
            while(!s.empty()) {
                auto t = s.top();
                if(temperatures[i] <= temperatures[t]) {
                    break;
                } else {
                    //当前的元素大于堆栈的栈顶的元素时,保存栈顶元素的结果并出栈,
                    res[t] = i - t;
                    s.pop();
                }
            }
            s.push(i); //把最新的元素保存到堆栈
        }
        return res;
    }
};

题目链接

https://leetcode-cn.com/problems/daily-temperatures/description/

上一篇 下一篇

猜你喜欢

热点阅读