Skip to content

Commit 5faffd1

Browse files
authored
Create number-of-visible-people-in-a-queue.cpp
1 parent 9ed9e2a commit 5faffd1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
vector<int> canSeePersonsCount(vector<int>& heights) {
7+
vector<int> result(size(heights));
8+
vector<int> stk;
9+
for (int i = 0; i < size(heights); ++i) {
10+
while (!empty(stk) && heights[stk.back()] <= heights[i]) {
11+
++result[stk.back()]; stk.pop_back();
12+
}
13+
if (!empty(stk)) {
14+
++result[stk.back()];
15+
}
16+
stk.emplace_back(i);
17+
}
18+
return result;
19+
}
20+
};
21+
22+
// Time: O(n)
23+
// Space: O(n)
24+
class Solution2 {
25+
public:
26+
vector<int> canSeePersonsCount(vector<int>& heights) {
27+
vector<int> result(size(heights));
28+
vector<int> stk;
29+
for (int i = size(heights) - 1; i >= 0; --i) {
30+
int cnt;
31+
for (cnt = 0; !empty(stk) && heights[stk.back()] < heights[i]; ++cnt) {
32+
stk.pop_back();
33+
}
34+
result[i] = !empty(stk) ? cnt + 1 : cnt;
35+
stk.emplace_back(i);
36+
}
37+
return result;
38+
}
39+
};

0 commit comments

Comments
 (0)