题解 | #牛的生长情况# 单调栈
牛的生长情况
https://www.nowcoder.com/practice/5f67258999bd4e61a361f4d3017a3fd4
知识点
单调栈
思路
题意是寻找右边第一个比当前值大的数,这可以用单调栈维护,时间复杂度为
AC code (C++)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weights int整型vector
* @return int整型vector
*/
vector<int> weightGrowth(vector<int>& weights) {
// 单调栈
int n = weights.size();
vector<int> r(n, -1);
stack<int> stk;
for (int i = n - 1; i >= 0; i --) {
while (stk.size() and weights[stk.top()] <= weights[i]) stk.pop();
if (!stk.empty()) r[i] = (stk.top() - i);
stk.push(i);
}
return r;
}
};
