File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments