1944. 队列中可以看到的人数 - 力扣(LeetCode)
1、一个人能看到的人要么比他自己高,要么比他自己矮
2、一个人最多只能看到一个比自己高的人
那可以倒序遍历height 数组,单调栈中降序,a若能弹出b说明b左边第一个比b高的人是a,那么a就能看到b。当while循环结束,如果栈不为空,说明栈顶是a右边第一个比自己高的人,a能看到他
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& hei) {
int n = hei.size();
vector<int> ans(n);
stack<int> sta;
for (int i = n - 1; i >= 0; i--) {
while (!sta.empty() && hei[i] > hei[sta.top()]) {
ans[i]++;
sta.pop();
}
if (!sta.empty()) {
ans[i]++;
}
sta.push(i);
}
return ans;
}
};