CPP版
牛客网题目链接
- 主要参照AcWing基础课讲的单调栈,注意这里统计的是下标位置而不是值。
class Solution {
public:
vector<vector<int> > foundMonotoneStack(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> res(n, vector<int>(2));
stack<int> stk;
for(int i = 0; i < n; i++){
while(stk.size() && nums[stk.top()] >= nums[i]) stk.pop();
if(stk.empty()) res[i][0] = -1;
else res[i][0] = stk.top();
stk.push(i);
}
stk = stack<int>();
for(int i = n-1; i >= 0; i--){
while(stk.size() && nums[stk.top()] >= nums[i]) stk.pop();
if(stk.empty()) res[i][1] = -1;
else res[i][1] = stk.top();
stk.push(i);
}
return res;
}
};