[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
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | # 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步