力扣 739. 每日温度

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

题目

  • 给定一个数组,表示每天的天气
  • 返回一个数组,index i 表示几天后比当前的温度要高,没有则为 0

思路

  • 维护一个单调递减栈,若当前的温度比栈顶大,则更新栈顶 index 的值

代码

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        int n = temperatures.size();
        vector<int> ans(n);
        stack<int> st;
        st.push(0);
        for (int i = 1; i < temperatures.size(); i++) {
            while (st.size() && temperatures[st.top()] < temperatures[i]) {
                int top_index = st.top();
                ans[top_index] = i - top_index;
                st.pop();
            }
            st.push(i);
        }

        return ans;
    }
};

你可能感兴趣的:(力扣热题,100,leetcode,算法)