0
点赞
收藏
分享

微信扫一扫

力扣 739. 每日温度

题目来源:https://leetcode.cn/problems/daily-temperatures/description/

C++题解:使用单调栈。栈里存放元素的索引,只要拿到索引就可以找到元素。

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int len = temperatures.size();
        vector<int> result(len, 0);
        stack<int> stk;
        stk.push(0);
        for(int i = 1; i < len; i++) {
            if(temperatures[i] < temperatures[stk.top()]) {
                // 如果新元素小于栈顶的元素,把它放进栈顶,成金字塔状。
                stk.push(i);
            }
            else {
                // 如果栈顶加入了更大的元素,下面的元素就得弹出来,弹出来的时候顺便更新该位置的result,用新索引减去该位置的索引。
                while(!stk.empty() && temperatures[i] > temperatures[stk.top()]){
                    result[stk.top()] = i - stk.top();
                    stk.pop();
                }
                stk.push(i);
            }
        }
        // 没有更新result的元素,保持0.
        return result;
    }
};
举报

相关推荐

0 条评论