【LeetCode題解】739.Daily Temperatures(每日溫度)(棧)

目錄

題目描述

解題思路

代碼實現

題目地址:https://leetcode-cn.com/problems/daily-temperatures


題目描述

Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

根據每日氣溫列表,請重新生成一個列表,對應位置的輸入是你需要再等待多久溫度纔會升高超過該日的天數。如果之後都不會升高,請在該位置用 0 來代替。

例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:氣溫 列表長度的範圍是 [1, 30000]。每個氣溫的值的均爲華氏度,都是在 [30, 100] 範圍內的整數。

解題思路

最簡單的辦法就是O(n^2)複雜度的遍歷……顯然太慢了 因爲重複遍歷了很多很多很多次

所以想到利用棧來記錄一個非遞減的序列。這裏引用官方的題解⬇️

我們需要找到比當前 T[i] 溫度更高的位置,那麼必須要記錄哪些信息?
我們試着找到 T[0] 過後溫度升高的位置。如果知道 T[10]=50,則 T[20]=50 是無效信息,因爲 T[i] 在 T[20] 以前已經到達了 50。如果 t[20]=100 將是有用的信息,因爲如果 t[0]=80,那麼 T[20] 將有可能是它的下一個溫度升高的位置,而 T[10] 則不可能是。
因此,我們需要記住一個索引的列表,索引代表的溫度嚴格遞增。我們可以利用棧來實現這樣的效果。

算法:

我們用棧記錄索引,滿足 T[stack[-1]] < T[stack[-2]] < ...,其中 stack[-1] 是棧的頂部,stack[-2] 是從頂部開始的第二個元素,依此類推;我們將在處理每個 T[i] 時保持 stack[-1] > stack[-2] > ...。
我們通過當前溫度和棧頂索引所代表的溫度比較來找到溫度升高的位置
舉個例子:我們反向遍歷處理 t=[73,74,75,71,69,72,76,73] ,通過看棧元素的變化來理解是如何工作的。爲了清楚 stack 只包含索引 i,但是將把 T[i] 的值寫在旁邊的括號中,例如 0 (73)。
當 i = 7,stack = [7 (73)]。ans[i] = 0。
當 i = 6,stack = [6 (76)]。ans[i] = 0。
當 i = 5,stack = [5 (72), 6 (76)]。ans[i] = 1。
當 i = 4,stack = [4 (69), 5 (72), 6 (76)]。ans[i] = 1。
當 i = 3,stack = [3 (71), 5 (72), 6 (76)]。ans[i] = 2。
當 i = 2,stack = [2 (75), 6 (76)]。ans[i] = 4。
當 i = 1,stack = [1 (74), 2 (75), 6 (76)]。ans[i] = 1。
當 i = 0,stack = [0 (73), 1 (74), 2 (75), 6 (76)]。ans[i] = 1。

作者:LeetCode
鏈接:https://leetcode-cn.com/problems/daily-temperatures/solution/mei-ri-wen-du-by-leetcode/

代碼實現(C++)

正序遍歷(比反向慢):

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        stack<int> helpstack;
        vector<int> res(T.size(),0);
        for(int i=0; i<T.size(); i++){
            while(!helpstack.empty() && T[i]>T[helpstack.top()]){
                res[helpstack.top()] = i - helpstack.top();
                helpstack.pop();
            }
            helpstack.push(i);
        }
        return res;
    }
};

反向遍歷:

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        stack<int> helpstack;
        vector<int> ans(T.size());
        for(int i=T.size()-1; i>=0; i--){
            while(!helpstack.empty() && T[i]>=T[helpstack.top()]){
                helpstack.pop();
            }
            ans[i]=helpstack.empty()?0:helpstack.top()-i;
            helpstack.push(i);
        }
        return ans;
    }
};

 

發佈了50 篇原創文章 · 獲贊 54 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章