[Leetcode 739]*還有幾天會升溫 Daily Temperatures
阿新 • • 發佈:2018-11-11
【題目】
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]
[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]
.
還有幾天會升溫。
https://leetcode.com/problems/daily-temperatures
【思路】
暴力求解,用時太長了……參考答案用stack
【程式碼】
堆疊,倒序比較,當
1、stack不為空,T[i-1]>T[i],證明不會升溫,pop出棧跳出。進行步驟2
2、判斷stack是否為空,空棧無條件滿足返回0,否則【頂點(升溫點)-迴圈數i 】為天數
3、把i壓入棧。
class Solution { public int[] dailyTemperatures(int[] T) { int[] ans = new int[T.length]; Stack<Integer> stack = new Stack(); for (int i = T.length - 1; i >= 0; --i) {while (!stack.isEmpty() && T[i] >= T[stack.peek()]) stack.pop(); ans[i] = stack.isEmpty() ? 0 : stack.peek() - i; stack.push(i); } return ans; } }
方便理解
class Solution { public int[] dailyTemperatures(int[] T) { int tmp[]=new int[T.length]; Arrays.fill(tmp, 1); tmp[T.length-1]=0; for(int i=0;i<T.length-1;i++){ int j=i+1; while(T[j]<=T[i]){ ++j; tmp[i]++; if(j>=T.length){ break; } } tmp[i]=j<T.length?tmp[i]:0; } return tmp; } }