LeetCode 1944. Number of Visible People in a Queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> canSeePersonsCount(vector<int>& heights) {
int n = heights.size();
vector<int> ans(n);
stack<int> stk;
for (int i = 0; i < n; ++i) {
int h = heights[i];
while (!stk.empty() && heights[stk.top()] <= h)
++ans[stk.top()], stk.pop();
if (!stk.empty())
++ans[stk.top()];
stk.emplace(i);
}
return ans;
}
};