题解 | #牛的生长情况#
牛的生长情况
https://www.nowcoder.com/practice/5f67258999bd4e61a361f4d3017a3fd4
知识点:单调栈
思路:基本的单调栈思路,这里求的第n天后,因此还需要最大值的坐标(最大值)减去当前的坐标,
编程语言:java
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weights int整型一维数组 * @return int整型一维数组 */ public int[] weightGrowth (int[] weights) { // write code here Stack<Integer> stack = new Stack<>(); int[] result = new int[weights.length]; for(int i=0;i<weights.length;i++){ result[i] = -1; } //遍历数组 for(int i=0;i<weights.length;i++){ //当元素大于栈顶元素,说明找到栈里元素的最大值 while(!stack.isEmpty() && weights[i]>weights[stack.peek()]){ //栈中的元素存储的下标赋值这次的最大值的下标 //题目要求的是第几天后,并非x下标,因此减去当前的下标即可 int index = stack.pop(); result[index] = i - index; } //否则就是直接入栈 stack.push(i); } return result; } }