简介
如果用暴力岂不是太不优雅了. 有些问题可以使用单调栈来进行计算.
简单思想
构建一个栈, 栈是一个有顺序的, 里面有一个while循环,然后 如果满足一定的条件, 将会一直弹出.
code
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& T) {
stack<int> s;
vector<int> res(T.size(), 0);
int len = T.size();
for(int i=0; i<len; i++){
while(!s.empty() && T[s.top()] < T[i]){
res[s.top()] = i - s.top();
s.pop();
}
s.push(i);
}
return res;
}
};
class Solution {
public int[] dailyTemperatures(int[] T) {
Deque<Integer> stack = new ArrayDeque<>();
int [] res = new int[T.length];
for(int i = 0; i<T.length; i++){
while(!stack.isEmpty() && T[stack.peek()] < T[i]){
int idx = stack.pop();
res[idx] = i - idx;
}
stack.push(i);
}
return res;
}
}