Number of Visible People in a Queue LeetCode solution in C++

1
class Solution {
2
public:
3
vector<int> canSeePersonsCount(vector<int> &h) {
4
vector<int> ans;
5
stack<int> s;
6
int a = 0;
7
for (int i = h.size() - 1; i >= 0; i--) {
8
if (s.empty()) {
9
ans.push_back(a);
10
s.push(h[i]);
11
a++;
12
} else {
13
if (s.top() > h[i]) {
14
ans.push_back(1);
15
s.push(h[i]);
16
a++;
17
} else {
18
int b = 0;
19
while (!s.empty() && s.top() < h[i]) {
20
s.pop();
21
a--;
22
b++;
23
}
24
if (!s.empty()) b++;
25
ans.push_back(b);
26
s.push(h[i]);
27
a++;
28
}
29
}
30
}
31
reverse(ans.begin(), ans.end());
32
return ans;
33
}
34
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0