【每日一LeetCode】1944. 队列中可以看到的人数 【单调栈 + 逆序遍历】

71 阅读1分钟

题目链接

image.png

image.png

image.png


image.png

Python3

class Solution:
    def canSeePersonsCount(self, heights: List[int]) -> List[int]:
        n = len(heights)
        res  = [0] * n 
        stack = [] # 单调增栈  维护  
        for i in range(n - 1, -1, -1): # 从 后 往前 遍历
            while stack and heights[i] > stack[-1]: # 维护 从栈底到栈顶  身高依次递减 栈 
                res[i] += 1
                stack.pop()
            if stack: # 右侧第一个 高于heights[i] 的人 (若有)  第 i 个人 必定能看到
                res[i] += 1
            
            stack.append(heights[i])
        return res

image.png

C++

class Solution {
public:
    vector<int> canSeePersonsCount(vector<int>& heights) {
        int n = heights.size();
        vector<int> res(n, 0);
        vector<int> stk;
        for (int i = n - 1; i >= 0; --i){
            while (!stk.empty() && heights[i] > stk.back()){
                res[i] += 1;
                stk.pop_back();
            }
            if (!stk.empty()){
                res[i] += 1;
            }
            stk.emplace_back(heights[i]);
        }
        return res;
    }
};
class Solution {
public:
    vector<int> canSeePersonsCount(vector<int>& heights) {
        int n = heights.size();
        vector<int> res(n, 0);
        stack<int> stk;
        for (int i = n - 1; i >= 0; --i){
            while (!stk.empty() && heights[i] > stk.top()){
                res[i] += 1;
                stk.pop();
            }
            if (!stk.empty()){
                res[i] += 1;
            }
            stk.push(heights[i]);
        }
        return res;
    }
};