LC.P1944[队列中可以看到的人数] 方法一:单调栈123456789101112131415161718class Solution { public int[] canSeePersonsCount(int[] heights) { int n = heights.length; int[] ans = new int[n]; Deque<Integer> stack = new ArrayDeque<>(); for (int i = n - 1; i >= 0; --i) { while (!stack.isEmpty() && stack.peek() < heights[i]) { stack.pop(); ans[i]++; } if (!stack.isEmpty()) { ans[i]++; } stack.push(heights[i]); } return ans; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$ 方法二:数组实现单调栈1234567891011121314151617class Solution { public int[] canSeePersonsCount(int[] heights) { int n = heights.length, tt = -1; int[] ans = new int[n], stack = new int[n]; for (int i = n - 1; i >= 0; --i) { while (tt > -1 && stack[tt] < heights[i]) { --tt; ans[i]++; } if (tt > -1) { ans[i]++; } stack[++tt] = heights[i]; } return ans; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$