题目:739. 每日温度
思路:从后往前遍历,维护一个单调递减的栈。时间复杂度为0(n)。
C++版本:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n=temperatures.size();
vector<int> v(n,0);
//维护一个单调递减的栈
stack<int> st;
//栈底元素,避免出界
st.push(n);
for(int i=n-1;i>=0;i--){
//不是栈底且当前元素比栈顶元素对应的值大
while(st.top()!=n&&temperatures[i]>=temperatures[st.top()]){
st.pop();
}
//不是栈底元素
if(st.top()!=n){
v[i]=st.top()-i;
}
st.push(i);
}
return v;
}
};
JAVA版本:相关数据结构知识可以参考:JAVA数据结构专栏
class Solution {
public int[] dailyTemperatures(int[] temperatures) {
int n=temperatures.length;
int[] v=new int[n];
//维护一个单调递减的栈
//Deque<Integer> qu=new LinkedList<Integer>();//两种用一个即可
Deque<Integer> qu=new ArrayDeque<Integer>();
栈底元素,避免出界
qu.addLast(n);
for(int i=n-1;i>=0;i--){
//不是栈底且当前元素比栈顶元素对应的值大
while(qu.peekLast()!=n&&temperatures[i]>=temperatures[qu.peekLast()]){
qu.pollLast();
}
//是栈底元素
if(qu.peekLast()==n) v[i]=0;
else v[i]=qu.peekLast()-i;//不是栈底元素
qu.addLast(i);
}
return v;
}
}