题解 | #牛的生长情况#
牛的生长情况
https://www.nowcoder.com/practice/5f67258999bd4e61a361f4d3017a3fd4?tpId=354&tqId=10595832&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param weights int整型一维数组
* @return int整型一维数组
*/
public int[] weightGrowth (int[] weights) {
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;
}
}
本题知识点分析:
1.栈的出栈和入栈
2.队列
3.数组遍历
4.数学模拟
本题解题思路分析:
1.初始化栈stack,用于存储数组weights中元素的下标
2.如果stack不为空,并且栈顶元素小于当前元素值,弹出栈顶元素,增长权重为i-x
3.如果栈不为空,说明剩下元素没有增长,设置为-1


查看10道真题和解析