-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1944-number-of-visible-people-in-a-queue.js
95 lines (80 loc) · 1.8 KB
/
1944-number-of-visible-people-in-a-queue.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* @param {number[]} heights
* @return {number[]}
*/
const canSeePersonsCount = function(heights) {
const n = heights.length
const res = Array(n).fill(0)
const stk = []
for(let i = n - 1; i >= 0; i--) {
const cur = heights[i]
let del = 0
while(stk.length && cur > heights[stk.at(-1)]) {
del++
stk.pop()
}
res[i] = del + (stk.length ? 1 : 0)
stk.push(i)
}
return res
};
// another
/**
* @param {number[]} heights
* @return {number[]}
*/
const canSeePersonsCount = function(heights) {
const res = []
if(heights.length === 0) return res
const n = heights.length
const stk = []
for(let i = n - 1; i >= 0; i--) {
let del = 0
while(stk.length && heights[i] > heights[stk[stk.length - 1]]) {
stk.pop()
del++
}
res.push(del + (stk.length ? 1 : 0))
stk.push(i)
}
return res.reverse()
};
// another
/**
* @param {number[]} heights
* @return {number[]}
*/
const canSeePersonsCount = function(heights) {
const ans = new Uint32Array(heights.length);
const stack = [];
for (let i = heights.length - 1; i >= 0; i--) {
const h = heights[i];
let del = 0;
while (stack.length && stack[stack.length - 1] <= h) {
del++;
stack.pop();
}
ans[i] = del + (stack.length ? 1 : 0);
stack.push(h);
}
return ans;
};
// another
/**
* @param {number[]} heights
* @return {number[]}
*/
const canSeePersonsCount = function(heights) {
const stack = [], n = heights.length, res = Array(n)
for(let i = n - 1; i >= 0; i--) {
const h = heights[i]
let del = 0
while(stack.length && stack[stack.length - 1] <= h) {
stack.pop()
del++
}
res[i] = stack.length ? del + 1 : del
stack.push(h)
}
return res
};