题解 | 牛的生长情况
牛的生长情况
https://www.nowcoder.com/practice/5f67258999bd4e61a361f4d3017a3fd4
- 单调栈。
import java.util.*; public class Solution { public int[] weightGrowth (int[] weights) { final int n = weights.length; int[] ans = new int[n]; Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i < n; ++i) { while (!stack.isEmpty() && weights[i] > weights[stack.getLast()]) { final int idx = stack.removeLast(); ans[idx] = i - idx; } stack.addLast(i); } while (!stack.isEmpty()) { ans[stack.removeLast()] = -1; } return ans; } }