https://leetcode.com/problems/daily-temperatures/description/
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
int Tsize = T.size();
stack<int> tempStack;
vector<int>resut(Tsize, 0);
for(int i=0; i<Tsize; i++){
while (tempStack.size()&&T[tempStack.top()]<T[i]) {
resut[tempStack.top()] = i-tempStack.top();
tempStack.pop();
}
tempStack.push(i);
}
return resut;
}
};
初始化: 用堆栈 tempStack存储当日气温, 初始堆栈为空, 默认将第一天的气温压栈(压栈的其实是’第一天’,而不是第一天的气温,就是for循环的是才开始没有进入while,压栈一个元素). 用向量 result 存储结果, 初始化长度为气温报表长度, 默认值为零.
循环: 若栈顶那日的温度小于for循环的T[i], 这两日的时间间距, 就是更高温度出现时,’那日’ 需要等待的时间,然后弹出栈顶;然后继续不断进行while循环,往复弹出栈顶元素, 直到遍历完整张气温报表.
如果while进行不下去,然后把当前的T[i]的i压入栈
细节: 遍历完成后, 任有未弹栈的元素, 即说明此元素之后没有温度更高的日期, 故无法弹栈. 此时, 这一天的更高温期待时间为默认值 0.