[LeetCode] Daily Temperatures
阿新 • • 發佈:2018-02-02
instead break for each ide tput you stack 比較 clas , your output should be
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]
[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<intTLE>& 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
思路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