# [LeetCode] 739. Daily Temperatures 每日温度

2021年09月15日 阅读数：1

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.html

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]`.java

Note: The length of `temperatures` will be in the range `[1, 30000]`. Each temperature will be an integer in the range `[30, 100]`.python

Java: Stackpost

```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: Arraythis

```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:url

```# 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: wocode

```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++:htm

```// 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