1. 题目
根据每日 气温 列表,请重新生成一个列表,对应位置的输入是你需要再等待多久温度才会升高超过该日的天数。如果之后都不会升高,请在该位置用 0 来代替。
例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/daily-temperatures
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 单调栈解题
class Solution {
public:vector<int> dailyTemperatures(vector<int>& T) {vector<int> ans(T.size(),0);stack<int> stk;for(int i = 0; i < T.size(); ++i){while(!stk.empty() && T[stk.top()] < T[i]){ans[stk.top()] = i-stk.top();stk.pop();}stk.push(i);}return ans;}
};
class Solution {
public:vector<int> dailyTemperatures(vector<int>& T) {int i, n = T.size();vector<int> ans(n,0);stack<int> s;for(i = n-1; i >= 0; --i){while(!s.empty() && T[i] >= T[s.top()])//右边都没有大于我的,留着也没用s.pop();//删掉if(!s.empty())ans[i] = s.top()-i;s.push(i);}return ans;}
};
class Solution:# py3def dailyTemperatures(self, T: List[int]) -> List[int]:n = len(T)ans = [0]*ns = []for i in range(n-1,-1,-1):while len(s)>0 and T[i] >= T[s[-1]]:s.pop()if len(s)>0:ans[i] = s[-1]-is.append(i)return ans
572 ms 17.3 MB