LeetCode 739:每日溫度 Daily Temperatures

題目:

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

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

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].

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

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

解題思路:

最容易想到和理解的就是暴力窮舉,兩個指針,一個指針指向當前溫度,第二指針向後遍歷找到最近一個比當前溫度高的溫度,記錄兩個指針的索引差即可。可以說效率非常低了。

另一種方法是藉助棧倒序遍歷原數組,存入較高的溫度的索引,也很容易理解,時間複雜度爲 O(n)。其實現邏輯爲:

原數組:[73, 74, 75, 71, 69, 72, 76, 73],指針 i 從末尾向前遍歷,返回數組res=[0,0,0,0,0,0,0]

第一次遍歷: i = 7, T[i] = 73, stack = []
        棧爲空,res[7] = 0 ,73所在索引7入棧。stack = [7]

第二次遍歷: i = 6, T[i] = 76, stack = [7]
        棧頂對應索引7的溫度T[7]=76,76>73,索引7出棧,此時棧爲空,res[6] = 0。索引6入棧,stack = [6]

第三次遍歷: i = 5, T[i] = 72, stack = [6]
        棧頂對應索引6的溫度T[6]=76,72<76,滿足要求,當前索引5入棧。res[5] = 棧頂索引6 - 當前索引5 = 1, stack = [6,5]

第四次遍歷: i = 4, T[i] = 69, stack = [6,5]
        棧頂對應索引5的溫度T[5]=72,69<72,滿足要求,當前索引4入棧。res[4] = 棧頂索引5-當前索引4=1, stack = [6,5,4]

第五次遍歷: i = 3, T[i] = 71, stack = [6,5,4]
        棧頂對應索引的溫度T[4]=69,71>69,棧頂元素出棧。stack = [6,5]
        棧頂對應索引的溫度T[5]=72,滿足要求,當前索引3入棧。res[3] = 棧頂索引5-當前索引3=2, stack = [6,5,3]

第六次遍歷: i = 2, T[i] = 75, stack = [6,5,3]
        棧頂對應索引的溫度T[3]=71,75>71,棧頂元素出棧。stack = [6,5]
        棧頂對應索引的溫度T[5]=72,75>72,棧頂元素出棧。stack = [6]
        棧頂對應索引的溫度T[6]=76,75<76,滿足要求,當前索引2入棧。res[2] = 棧頂索引6-當前索引2=4, stack = [6,2]

第七次遍歷: i = 1, T[i] = 74, stack = [6,2]
        棧頂對應的溫度T[2]=75,滿足要求,當前索引1入棧。res[1] = 2-1=1, stack = [6,2,1]

第八次遍歷: i = 0, T[i] = 73, stack = [6,2,1]
        棧頂對應的溫度T[1]=74,滿足要求,當前索引0入棧。res[0] = 1-0=1, stack = [6,2,1,0]

遍歷結束: res = [1,1,4,2,1,1,0,0]

這種方法下,棧存入索引對應的溫度值始終按升序排列,當棧爲空時,證明當前溫度爲 從該溫度向後的所有溫度裏 最大的。

Java:

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int len=T.length;
        int[] res = new int[len];
        Stack<Integer> stack = new Stack<>();//初始化棧
        for (int i = len - 1; i >= 0; i--) {
            while (!stack.isEmpty() && T[stack.peek()] <= T[i]) {
                stack.pop();
            }
            if (stack.isEmpty()) res[i] = 0;
            else res[i] = stack.peek() - i;
            stack.push(i);
        }
        return res;
    }
}

事實上就這道題而言這並不是一個好方法,因爲提示已經明確規定了數據範圍:

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

最多30000個數據量,數據非常小,入棧出棧,獲取棧頂元素,判斷棧是否空,在數據量很少的情況下這些函數反覆調用,相對就佔用了很多運行時間,其最終評測運行總時間爲 109 ms。那麼如何優化?

由於所有數據值的範圍均在30到100之間,那麼意爲着按升序排列溫度的棧的大小 最大不會超過71(因爲從30到100只有71個元素)。那就可以不用棧這個需要反覆調用函數的數據結構。直接用長度爲71的數組順序存入索引即可,定義一個指針,索引減一代替出棧,索引加一併賦值代替入棧,索引是否溢出代替判斷棧是否爲空,無虛函數調用。

優化後:

總運行時間爲 4ms,降低了105毫秒

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int len = T.length;
        int[] res = new int[len], stack = new int[71];
        int index = -1;
        for (int i = len - 1; i >= 0; i--) {
            while (index >= 0 && T[stack[index]] <= T[i]) {
                index--;
            }
            if(index >= 0) res[i] = stack[index] - i;
            stack[++index] = i;
        }
        return res;
    }
}

Python:

python並沒有隊列、棧這種數據結構,因爲數組就可以做到先進先出、後進先出等操作。

class Solution:
    def dailyTemperatures(self, T: List[int]) -> List[int]:
        tLen = len(T)
        stack = []
        res = [0] * tLen
        for i in range(tLen - 1, -1, -1):
            while stack and T[i] >= T[stack[-1]]:
                stack.pop()
            if stack: res[i] = stack[-1] - i
            stack.append(i)
        return res

歡迎關注微.信公.衆號 一起學習:愛寫Bug

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章