题目考察的知识点是:
本题主要考察知识点是栈。
题目解答方法的文字分析:
我们可以使用一个单调栈维护weights数组的下标。遍历weights数组时,当weights[i]比栈的顶部对应的质量大时,更新答案数组ans[st.top()]=i-st.top(),并且将对应下标弹出栈。在栈顶下标对应的质量不大于当前weights[i]时,再将当前i入栈。
本题解析所用的编程语言:
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);
}
while (!stack.isEmpty()) {
res[stack.pop()] = -1;
}
return res;
}
}

京公网安备 11010502036488号