题解 | #牛的生长情况#
牛的生长情况
https://www.nowcoder.com/practice/5f67258999bd4e61a361f4d3017a3fd4
考察栈的应用。主要利用栈的特性解决,具体细节参看注释
完整Java代码如下所示
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weights int整型一维数组
* @return int整型一维数组
*/
public int[] weightGrowth (int[] weights) {
// write code here
int n = weights.length;
int[] res = new int[n];
Deque<Integer> stack = new ArrayDeque<>();
// 遍历数组
for (int i = 0; i < n; i++) {
// 弹出比当前元素小的栈顶元素,并计算增长距离
while (!stack.isEmpty() && weights[stack.peek()] < weights[i]) {
int x = stack.pop();
res[x] = i - x;
}
// 将当前元素入栈
stack.push(i);
}
// 处理栈中剩余的元素,设置增长距离为-1
while (!stack.isEmpty()) {
res[stack.pop()] = -1;
}
return res;
}
}

