【LeetCode】739. 每日温度

题目

739. 每日温度

思路

创建一个栈,遍历输入,如果栈为空则直接压入,如果栈非空且当前温度大于栈顶元素,则弹出栈顶元素,并且a[pre]=i-pre,pre为栈顶元素,如果当前温度小于栈顶元素,则直接压入栈中。

代码

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n=temperatures.size();
        vector<int>a(n);
        stack<int>v;
        for(int i=0;i<n;i++)
        {
            while(!v.empty() && temperatures[i]>temperatures[v.top()])
            {
                int pre=v.top();
                a[pre]=i-pre;
                v.pop();
            }
            v.push(i);
        }
            return a;
    }
};

你可能感兴趣的:(leetcode,算法)