1944. 队列中可以看到的人数

有 n 个人排成一个队列,从左到右 编号为 0 到 n - 1 。给你以一个整数数组 heights ,每个整数 互不相同,heights[i] 表示第 i 个人的高度。

一个人能 看到 他右边另一个人的条件是这两人之间的所有人都比他们两人 矮 。更正式的,第 i 个人能看到第 j 个人的条件是 i < j 且 min(heights[i], heights[j]) > max(heights[i+1], heights[i+2], …, heights[j-1]) 。

请你返回一个长度为 n 的数组 answer ,其中 answer[i] 是第 i 个人在他右侧队列中能 看到 的 人数 。


思路:单调栈。反过来想。从右向左看,若当前的H(i)>H(i+1)则,第i-1个人也看不到后续的人。即使用单调栈即可解决。
复杂度:O(N)

class Solution {
    public int[] canSeePersonsCount(int[] heights) {
        Deque<Integer> q = new ArrayDeque();
        int n = heights.length;
        int[] ans = new int[n];
        for(int i=n-1; i>=0; i--) {
            while(!q.isEmpty() && q.peek()<heights[i]) {
                q.pop();
                ans[i]++;
            }
            if(!q.isEmpty()) ans[i]++;
            q.push(heights[i]);
        }
        return ans;
    }
}

你可能感兴趣的:(算法,数据结构)