1. 程式人生 > >[LeetCode] Daily Temperatures

[LeetCode] Daily Temperatures

instead break for each ide tput you stack 比較 clas

Given a list of daily temperatures, produce a list 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 temperatures = [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].

給定一個溫度表,找出需要對於每一個溫度,多少天後的溫度比當前溫度高。將結果放入一個數組中。

思路1:遍歷2次溫度表,找出符合條件的天數。

復雜度為O(n^2) 超時

技術分享圖片
class Solution {
public:
    vector<int> dailyTemperatures(vector<int
>& temperatures) { vector<int> res(temperatures.size(), 0); for (int i = 0; i < temperatures.size(); i++) { for (int j = i + 1; j < temperatures.size(); j++) { if (temperatures[j] - temperatures[i] > 0) { res[i] = j - i;
break; } } } return res; } }; // TLE
TLE

思路2:使用一個stack來存儲待比較的元素,直到遇到符合條件的值後再一一出棧比較。只需要遍歷一次溫度表。

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& temperatures) {
        vector<int> res(temperatures.size(), 0);
        stack<pair<int, int>> stk;
        for (int i = 0; i < temperatures.size(); i++) {
            while (!stk.empty() && temperatures[i] > stk.top().first) {
                res[stk.top().second] = i - stk.top().second;
                stk.pop();
            }
            stk.push(make_pair(temperatures[i], i));
        }
        return res;
    }
};
// 233 ms

[LeetCode] Daily Temperatures