[LeetCode] 739. 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].

給一個每天溫度的數組,對於每一天,找出下一個比當前溫度大的元素,記錄它們之間的天數。

解法:棧,遞減棧Descending Stack,新建一個長度和T相等的數組res,來記錄天數。遍歷數組,如果棧為空,直接如棧。如果棧不為空,且當前數字大於棧頂元素,pop出棧頂元素,求出下標差,也就是升溫的天數,把這個差值記錄給棧頂元素在res中的位置。然后繼續看新的棧頂元素,直到當前數字小於等於棧頂元素停止。然后將當前數字入棧。最后返回res。

Java: Stack

public int[] dailyTemperatures(int[] temperatures) {
    Stack<Integer> stack = new Stack<>();
    int[] ret = new int[temperatures.length];
    for(int i = 0; i < temperatures.length; i++) {
        while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
            int idx = stack.pop();
            ret[idx] = i - idx;
        }
        stack.push(i);
    }
    return ret;
}

Java: Array

public int[] dailyTemperatures(int[] temperatures) {
    int[] stack = new int[temperatures.length];
    int top = -1;
    int[] ret = new int[temperatures.length];
    for(int i = 0; i < temperatures.length; i++) {
        while(top > -1 && temperatures[i] > temperatures[stack[top]]) {
            int idx = stack[top--];
            ret[idx] = i - idx;
        }
        stack[++top] = i;
    }
    return ret;
} 

Python:

# Time:  O(n)
# Space: O(n)

class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        result = [0] * len(temperatures)
        stk = []
        for i in xrange(len(temperatures)):
            while stk and \
                  temperatures[stk[-1]] < temperatures[i]:
                idx = stk.pop()
                result[idx] = i-idx
            stk.append(i)
        return result  

Python: wo

class Solution(object):
    def dailyTemperatures(self, T):
        """
        :type T: List[int]
        :rtype: List[int]
        """
        st = []
        res = [0] * len(T)
        for i in xrange(len(T)):
            if not st or T[i] <= T[st[-1]]:
                st.append(i)
            else:
                while st and T[i] > T[st[-1]]: 
                    j = st.pop()
                    res[j] = i - j
                st.append(i)   
                                        
        return res  

C++:

// Time:  O(n)
// Space: O(n)

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> result(temperatures.size());
        stack<int> stk;
        for (int i = 0; i < temperatures.size(); ++i) {
            while (!stk.empty() &&
                   temperatures[stk.top()] < temperatures[i]) {
                const auto idx = stk.top(); stk.pop();
                result[idx] = i - idx;
            }
            stk.emplace(i);
        }
        return result; 
    }
};

    

類似題目:

[LeetCode] 496. Next Greater Element I 下一個較大的元素 I

 

 

All LeetCode Questions List 題目匯總


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM