題目:739. 每日溫度
根據每日 氣溫 列表,請重新生成一個列表,對應位置的輸出是需要再等待多久溫度纔會升高超過該日的天數。如果之後都不會升高,請在該位置用 0 來代替。
例如,給定一個列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的輸出應該是 [1, 1, 4, 2, 1, 1, 0, 0]。
提示:氣溫 列表長度的範圍是 [1, 30000]。每個氣溫的值的均爲華氏度,都是在 [30, 100] 範圍內的整數。
這幾天我要光明正大咕咕咕了,要準備下周的筆試面試,海投回信結果從1/10變成3/14,枯了。
思路:單調棧
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
vector<int> ans(T.size());
stack<int> sk;
for (int i=0;i<T.size();i++){
while (!sk.empty() && T.at(i)>T.at(sk.top())){
int index=sk.top();
sk.pop();
ans.at(index)=i-index;
}
sk.push(i);
}
return ans;
}
};
運行結果: