1. 程式人生 > 其它 >【單調棧】-每日溫度[mid]

【單調棧】-每日溫度[mid]

題目

  1. 每日溫度

給定一個整數陣列 temperatures ,表示每天的溫度,返回一個數組 answer ,其中 answer[i] 是指在第 i 天之後,才會有更高的溫度。如果氣溫在這之後都不會升高,請在該位置用 0 來代替。

思路

單調棧的思路
逆向尋找下一個更大的元素,儲存好下標索引,對應的位置直接相減!

程式碼

class Solution:
    def dailyTemperatures(self, t: List[int]) -> List[int]:
        n = len(t)
        st = []
        cnt = 1
        res = [0]*n
        for i in range(n-1,-1,-1):
            v =t[i]
            while st and t[st[-1]]<=v:
                st.pop()
            if st:
                pre = st[-1]
                res[i] = pre-i
            st.append(i)
        return res

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& t) {
        int n = t.size();
        vector<int> res(n,0);
        stack<int> st;
        int pre = 0;
        for(int i = n-1;i>=0;--i)
        {
            while (!st.empty() && t[st.top()]<=t[i])
            {
                st.pop();
            }
            if (!st.empty())
            {
                pre = st.top();
                res[i] = pre - i;
            }
            st.push(i);
        }
        for(int i=0;i<n;i++)
        {
            cout<<res[i]<<endl;
        }
        return res;
    }
};