Skip to content

Commit a14e99f

Browse files
authored
Create 2282-number-of-people-that-can-be-seen-in-a-grid.js
1 parent 244b485 commit a14e99f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number[][]} heights
3+
* @return {number[][]}
4+
*/
5+
const seePeople = function(heights) {
6+
const m = heights.length, n = heights[0].length
7+
const res = Array.from({ length: m }, () => Array(n).fill(0))
8+
9+
for(let i = 0; i < m; i++) {
10+
const stk = []
11+
for(let j = n - 1; j >= 0; j--) {
12+
let del = 0
13+
14+
while(stk.length && heights[i][j] > heights[i][stk[stk.length - 1]]) {
15+
del++
16+
stk.pop()
17+
}
18+
res[i][j] = del + (stk.length ? 1 : 0)
19+
if(stk.length && heights[i][j] === heights[i][stk[stk.length - 1]]) continue
20+
stk.push(j)
21+
}
22+
}
23+
24+
for(let j = 0; j < n; j++) {
25+
const stk = []
26+
for(let i = m - 1; i >= 0; i--) {
27+
let del = 0
28+
29+
while(stk.length && heights[i][j] > heights[stk[stk.length - 1]][j]) {
30+
del++
31+
stk.pop()
32+
}
33+
res[i][j] += del + (stk.length ? 1 : 0)
34+
if(stk.length && heights[i][j] === heights[stk[stk.length - 1]][j]) continue
35+
stk.push(i)
36+
}
37+
}
38+
39+
return res
40+
};

0 commit comments

Comments
 (0)