File tree 1 file changed +19
-38
lines changed
scripts/algorithms/N/Number of Visible People in a Queue
1 file changed +19
-38
lines changed Original file line number Diff line number Diff line change 1
- var visibleToRight = function ( heights ) {
2
- const result = new Array ( heights . length ) . fill ( 0 )
1
+ // Runtime: 167 ms (Top 85.71%) | Memory: 73.90 MB (Top 15.71%)
2
+
3
+ /**
4
+ * @param {number[] } heights
5
+ * @return {number[] }
6
+ */
7
+ var canSeePersonsCount = function ( heights ) {
3
8
const stack = [ ]
9
+ const answer = new Array ( heights . length ) . fill ( 0 )
10
+
11
+ for ( let i = 0 ; i < heights . length ; i ++ ) {
12
+ while ( stack . length && heights [ i ] > heights [ stack [ stack . length - 1 ] ] ) {
13
+ answer [ stack . pop ( ) ] ++
14
+ }
4
15
5
- let i = heights . length - 1
6
-
7
- // loop from right to left
8
- while ( i >= 0 ) {
9
- let popCount = 0
10
-
11
- // Keep Popping untill top ele is smaller
12
- while ( stack . length > 0 && stack [ stack . length - 1 ] [ 0 ] < heights [ i ] ) {
13
- stack . pop ( )
14
- popCount += 1
16
+ if ( stack . length ) {
17
+ answer [ stack [ stack . length - 1 ] ] ++
15
18
}
16
-
17
- /////////////////////
18
- /// After Popping ///
19
- ////////////////////
20
-
21
- // Case1: if ALL elements got popped
22
- if ( stack . length === 0 )
23
- result [ i ] = popCount // mark
24
-
25
- // Case2: if NO elements were popped
26
- else if ( popCount === 0 )
27
- result [ i ] = 1 // mark
28
-
29
- // Case3: if SOME elements were popped
30
- else
31
- result [ i ] = popCount + 1 // mark
32
-
33
- // store
34
- stack . push ( [ heights [ i ] , popCount ] )
35
-
36
- i -= 1
19
+
20
+ stack . push ( i )
37
21
}
38
-
39
- return result
40
- }
41
- var canSeePersonsCount = function ( heights ) {
42
- return visibleToRight ( heights )
22
+
23
+ return answer
43
24
} ;
You can’t perform that action at this time.
0 commit comments