mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
28 lines
864 B
Markdown
28 lines
864 B
Markdown
![]() |
# [739. Daily Temperatures](https://leetcode.com/problems/daily-temperatures/)
|
|||
|
|
|||
|
# 思路
|
|||
|
|
|||
|
数组里每个元素的右边第一个比它大的元素,若找不到用0填充。典型的单调栈,关于单调栈我已经总结过了([戳我](../algorithm/array/monotonic_stack_queue.md)),这里不再赘述,直接给出代码。
|
|||
|
|
|||
|
时空复杂度均为O(N)
|
|||
|
|
|||
|
# C++
|
|||
|
``` C++
|
|||
|
class Solution {
|
|||
|
public:
|
|||
|
vector<int> dailyTemperatures(vector<int>& T) {
|
|||
|
int n = T.size();
|
|||
|
vector<int>res(T.size(), 0);
|
|||
|
|
|||
|
stack<int>mono_stk;
|
|||
|
for(int i = n - 1; i >= 0; i--){ // 反向遍历
|
|||
|
while(!mono_stk.empty() && T[i] >= T[mono_stk.top()])
|
|||
|
mono_stk.pop();
|
|||
|
if(!mono_stk.empty())
|
|||
|
res[i] = mono_stk.top() - i;
|
|||
|
mono_stk.push(i);
|
|||
|
}
|
|||
|
return res;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|