自己思路:
想到用兩個棧,一個維護元素、另一個維護下標。但是還是無法處理有重復元素的問題(用哈希表來存儲的時候)。所以就看了答案的思路。
答案思路:
從前往后遍歷,維護一個單調棧。棧存放數(shù)組的下標。
①棧為空 or 當前下標元素 <= 棧頂元素,入棧;
②當前下標元素 > 棧頂元素,就出棧,并計算它們的下標之差,存入到這個出棧元素對應的數(shù)組里面。
代碼:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> ans(n); // 設置存放當前下標溫度之后的幾天可以遇到高溫度
stack<int> st; // 單調棧,用來存放元素下標
int i = 0;
while( i != temperatures.size()) {
int t = temperatures[i]; // 獲取當前下標元素
// 如果棧為空 or t<= 棧頂元素,就入棧,并把指針后移
if(st.empty() || t <= temperatures[st.top()]){
st.push(i);
i++;
}
// 如果 t>棧頂元素,那么就是棧頂這個溫度找到了比它高的溫度,出棧棧頂元素并計算它們之間的間隔天數(shù),存入到與棧頂元素相關的數(shù)組中。
else if (t > temperatures[st.top()]) {
int loc = st.top();
st.pop();
ans[loc] = i - loc;
}
}
return ans;
}
};
運行結果:
文章來源:http://www.zghlxwxcb.cn/news/detail-673537.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-673537.html
到了這里,關于leetcode739. 每日溫度 單調棧的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!